11

I'm trying to add multiple plots on one axis and I would like them to have different opacities (e.g. 0.1, 0.2 etc.). I have tried with different options:

  1. The only thing that actually compiles is foreach with count variable. What it doesn't do is change the opacity of the plots:

    \documentclass[a4paper,12pt]{article}
    \usepackage{pgfplots}
    \begin{document}
        \begin{tikzpicture}
            \begin{axis}[width=0.8\textwidth]
                \foreach [count=\op] \x in{1,...,10} {
                \addplot[thick, color=blue, opacity={0.1*\op}] table[x index = 0, y index = \op, col sep=tab]{data.csv};
                }
            \end{axis}
        \end{tikzpicture}
    \end{document}
    
  2. pgfmathsetmacro, doesn't compile:

    \documentclass[a4paper,12pt]{article}
    \usepackage{pgfplots}
    \begin{document}
        \begin{tikzpicture}
            \begin{axis}[width=0.8\textwidth]
                \foreach \x in{1,...,10} {
                \pgfmathsetmacro\op{\x*0.1}
                \addplot[thick, color=blue, opacity={\op}] table[x index = 0, y index = \x, col sep=tab]{data.csv};
                }
            \end{axis}
        \end{tikzpicture}
    \end{document}
    
  3. Using evaluate, doesn't compile:

    \documentclass[a4paper,12pt]{article}
    \usepackage{pgfplots}
    \begin{document}
        \begin{tikzpicture}
            \begin{axis}[width=0.8\textwidth]
                  \foreach [evaluate=\x as \op using {0.1*\x}] \x in{1,...,10} {
                  \addplot[thick, color=blue, opacity={\op}] table[x index = 0, y index = \x, col sep=tab]{data.csv};
                  }
            \end{axis}
        \end{tikzpicture}
    \end{document}
    

I am sure there is a possibility it's just that I have not had too much experience with pgfplots yet and am probably missing something obvious.

Data file can be accessed here: data.csv

14

For applications like this, you need to use \pgfplotsinvokeforeach instead of the normal \foreach loop. The issue with the normal \foreach is that PGFPlots first collects all the \addplot commands generated within your loop and executes them at a later point, when the variable \op is set to 1 for all the plots. \pgfplotsinvokeforeach makes sure that the value of the loop variable is stored with the \addplot command.

To get your example to work, use the following syntax (note that you have to use #1 instead of a named macro for the loop variable):

\pgfplotsinvokeforeach{1,...,10} {
            \addplot[thick, color=blue, opacity={0.1*#1}] table ...
}

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.