I'm trying to plot a figure with TikZ. I have a few .txt files with the coordinates of the curves that I want to plot, in a list such as
file2.txt,
file4.txt,
...
file30.txt
and I want to add them with \plot
file in a axis environment. Also, I'd like to put them with different colors, creating a shading effects, let's say from blue to red.
In short, I want to create a sort of contour plot, but since I don't have the 3D function I have to import the coordinates.
I wrote this code, where I use two variables in \foreach
, one for the file name, \x, and one for the shading of the color, \y, (see lines 'Original Idea'). It doesn't work because of some kind of trouble between \foreach and the axis environment.
I thought about other options, such as to explicate a relation between \x and \y (see code lines), use \pgfplotsinvokeforeach
or an other trick with \edef
but they doesn't work for different reasons:
-
if I explicit the relation it seem like it doesn't want to calculate 3*\x (undefined control sequence)
-
with
\pgfplotsinvokeforeach
it says 'illegal unit of measure' -
same for
\edef
I read some topics on the use of \pgfplotsinvokeforeach
and the trick with \edef
but probably I haven't understood correctly how to use them in my code.
Can you give me a solution? Better it would be if you give me the corrections for all the 4 possible cases I proposed 🙂
Here's the code
\documentclass{article}
\usepackage{pgf,pgfsys,pgffor}
\usepackage{pgfplots}
\usepackage{tikz}
\begin{document}
\begin{figure}
\begin{tikzpicture}
\newcommand{\filename}{./figure/regionDep0/orthogonal}
\begin{axis}[
xmin=0, xmax=1, ymin=0, ymax=1, width=8cm, height=8cm]
% Original idea: not working
\foreach \x/\y in {2/0,4/7,...,30/98}
{
\plot[color=blue!\y!red] file {\filename \x.txt};
}
%
% % substituting \y as function of \x: not working
% \foreach \x in {2,4,...,30}
% {
% \plot[color=blue!3*\x!red] file {\filename \x.txt};
% }
%
% % Trying with \pgfplotsinvokeforeach: not working
% \pgfplotsinvokeforeach{2,4,...,30}
% {
% \plot [color=blue!3*#1!red] file {\filename #1.txt};
% }
%
% % Trying with \edef\temp{...}: not working
% \foreach \x/\y in {2/0,4/7,...,30/98}
% {
% \edef\temp{\noexpand\plot [color=blue!\y!red] file {\filename \x.txt};}
% \temp
% }
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}
Best Answer
If you're using an
axis
environment, which is provided by the PGFPlots package, you should use\addplot
instead of\plot
.To use a different colour for each plot, one option might be using the
mesh
plot type together withpoint meta=explicit
andmeta expr=\i
. This allows the use of colormaps instead of being limited tocolorA!<value>!colorB
expressions:Alternatively (and probably better), you can use the
contour prepared
plot style if you put all contours into a single file. That way, you can even get labels on the contours (the labels can be adjusted or switched off, of course):