# [Tex/LaTex] Force pgfplots to draw legend according to cycle list instead of the first plots

gnuplotlegendpgfplotstikz-pgf

I use pgfplots to plot multiple curves from a file. The graph is plotted in two steps

1. Draw only the marks, taking the original values from the file
2. Draw only the lines, approximating the curve of the values with gnuplot

So it looks something like this (the following only illustrates the reason why I face this problem):

\foreach \r in {1,...,9} { % first loop, marks
plot table [x index=0, y index=\r]{file.csv};
}
\foreach \rg in {2,...,10} { % second loop, lines (gnu starts with 1)
gnuplot [raw gnuplot]
{
f(x)=a*x+b;
a=1; b=0.1;
fit f(x) 'file.csv' using 1:\rg\space every ::1 via a;
plot [x=0:10] f(x);
};
}


Now the problem is that pgfplot seems to use the style of the first few plots it comes across. This leaves all legend entries without lines since the style of the first plots is only marks.

Therefore, the following MWE produces an output like this, leaving the legend entries without lines:

\documentclass{standalone}
\usepackage{pgfplots}

\pgfplotscreateplotcyclelist{mycyclelist}{
{loosely dashed, blue}, {red}
}

\begin{document}
\begin{tikzpicture}
\begin{axis}[cycle list name = mycyclelist, legend entries={a, b}, legend pos=north west]
% only marks
coordinates
{
(0,0)
(10,5)
};
coordinates
{
(0,0)
(10,7)
};

% no markers
coordinates
{
(0,0)
(10,5)
};
coordinates
{
(0,0)
(10,7)
};
\end{axis}
\end{tikzpicture}
\end{document}


The option legend image post style is precisely what you need:

\documentclass{standalone}
\usepackage{pgfplots}

\pgfplotsset{compat=1.10}

\pgfplotscreateplotcyclelist{mycyclelist}{
{loosely dashed, blue}, {red}
}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
cycle list name = mycyclelist,
legend entries={a, b},
legend pos=north west,
legend image post style={sharp plot},
]
% only marks
coordinates
{
(0,0)
(10,5)
};
coordinates
{
(0,0)
(10,7)
};

% no markers
coordinates
{
(0,0)
(10,5)
};

The list of options after legend image post style applies to every legend image and is independent of the plot style. Adding sharp plot essentially overrides the only marks statement - but only for legend images.