# Hide/Replace labels with foreach

I am trying to make a command that will take a list of labels and use psfrag to hide them. in my figure X3 is removed but X1, X2 and X7 are still there.

OneDrive link to EPS file

Is there something special i need to do to use the foreach \thing counter in the \HideLabel command

\documentclass{article}
\usepackage[margin=20mm]{geometry}

\usepackage{pgffor}
\usepackage{psfrag}
\usepackage{graphicx}
\usepackage[runs=2,crop=off]{auto-pst-pdf}

\newcommand{\HideLabel}[1]{\foreach \thing in {#1} {%
\psfrag{\thing}{}}
}

\begin{document}

\begin{figure}[ht!]
\centering
\HideLabel{X1,X2,X7}
\psfrag{X3}{}
\includegraphics[scale=1]{Figure}
\caption{Figure caption}
\label{Figure1}
\end{figure}

\end{document}


The issue is that \psfrag works within the scope of the environment in which the \psfrag command is used. With \foreach a new scope is created for every item in the list, therefore the \psfrag commands do not reach the \includegraphics call (because the scope of the foreach items has already ended when \includegraphics is executed).

As an alternative you can use the list processing functionality of the etoolbox package, which does not create a new scope.

MWE (I made a small graph with seven labels, because I didn't want to download a file from an unknown location):

\documentclass{article}
\usepackage[margin=20mm]{geometry}

\usepackage{graphicx}
\usepackage{psfrag}
\usepackage[runs=2,crop=off]{auto-pst-pdf}
\usepackage{etoolbox}
\newcommand{\HideLabel}[1]{%
\renewcommand*{\do}[1]{\psfrag{##1}{}}%
\docsvlist{#1}%
}
\begin{document}
\begin{figure}[ht!]
\centering
\includegraphics[width=0.5\textwidth]{replacelabels}
\caption{Original figure}
\label{Figure1}
\end{figure}
\begin{figure}[ht!]
\centering
\HideLabel{X1,X2,X7}
\includegraphics[width=0.5\textwidth]{replacelabels}
\caption{Hidden labels}
\label{Figure2}
\end{figure}

\end{document}


Result:

• +1 Well done, I came to the same conclusion because the manual says A \psfrag command will remain in effect until its surrounding environment is exited. Therefore, you can define global \psfrags which will apply to every figure, or define \psfrags inside a a figure environment (for example) which apply to a single EPS file. But I didn't find a way to make psfrag global. – AndréC Oct 30 '19 at 7:09
• @AndréC It just means use \psfrag outside of a group (typically in the document preamble) – David Carlisle Oct 30 '19 at 9:28
• Thanks for the answer. However, I am getting an error saying "Command \do undefined." – Phildgg Oct 30 '19 at 9:38
• I do notice that it does still seem to work... – Phildgg Oct 30 '19 at 11:45
• @Phildgg that error is strange, because the \do command is defined by \usepackage{etoolbox}`. Do you get the error also when you run the example exactly as I posted here without any modifications (except for the filename of your image of course)? – Marijn Oct 30 '19 at 13:34