I like TikZ's capability to traverse multiple variables separated by a slash in the foreach
(as in the example below). I am looking for something equivalent in PGFplots? I saw in the documentation that say you can't nest the foreach
in PGFplots as you can in TikZ, but that only make this kind of feature more important.
Two other small issues:
I like the \x
notation so that is why I am using \pgfplotsforeachungrouped
. Is there a reason why I should be using pgfplotsinvokeforeach
instead?
Also, what is the correct syntax to be able to use a variable to define the list instead of having the actual list in the code. In the following I'd like to be able to reference \ListWithLabels
in the foreach
.
\documentclass{minimal}
\usepackage{pgfplots}
\newcommand*{\ListWithLabels}{-2/a, -1/b, 1/c, 2/d}
\newcommand*{\ListWithoutLabels}{-2, -1, 1, 2}
\begin{document}
\begin{tikzpicture}
\draw [->][gray, thin](-3,0) -- (3,0) node[blue, right] {$x$};
\draw [->][gray, thin](0,-3) -- (0,3) node[blue, above] {$y$};
%\foreach \x/\l in \ListWithLabels { % works
\foreach \x/\l in {-2/a, -1/b, 1/c, 2/d} {
\draw [thick, red]
(\x,-2pt) -- (\x,2pt)
node [red, above] {\l};
}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
minor tick num=0, axis y line=center, axis x line=middle,
xmin=-3, xmax=3, ymin=-3, ymax=3, xlabel=$x$, ylabel=$y$,
xtick={0}, xticklabels={}
]
%\pgfplotsinvokeforeach{-2, -1, 1, 2}{ % works
% \addplot [mark=none,color=red, thin, samples=2]
% coordinates{(#1,-0.05) (#1,0.05) };
%}
%\pgfplotsforeachungrouped \x in {\ListWithoutLabels}{ % does not work
\pgfplotsforeachungrouped \x in {-2, -1, 1, 2}{ % works
\addplot [mark=none,color=red, thick, samples=2]%
coordinates{ (\x,-0.08) (\x,0.08) };
}
%\pgfplotsforeachungrouped \x/\l in {-2/a, -1/b, 1/c, 2/d}{ % does not work
% \addplot [mark=none,color=red, thin, samples=2]%
% coordinates{ (\x,-0.05) (\x,0.05) }
% node [red, below] {\l};
%}
\end{axis}
\end{tikzpicture}
\end{document}
Update: I saw this post which explains that the macro in TikZ needs to be not be sourrouned by {}
. But that does not work for the PGF commands.
Here is another related post on pgfplotsinvokeforeach using a paramter
\foreach
macro is provided bypgffor
, not bytikz
and can be used forpgf
code as well. Also keep in mind thatpgfplots
is notpgf
, but a package based on it. However, its author is also a co-author of PGF/TikZ. You might want to change the 'PGF' in the title and text to 'pgfplots' and maybe remove the {pgf-core} tag. – Martin Scharrer♦ May 8 '11 at 20:19pgffor
? – Peter Grill May 8 '11 at 21:04\foreach
isn'ttikz
specific, but comes from the underlyingpgf
. Apparentlypgfplots
doesn't like the grouped macros used by\foreach
, so you can't use it. – Martin Scharrer♦ May 8 '11 at 21:29