[Tex/LaTex] How to modify the image of an legend entry

legendpgfplots

I have the following code

\documentclass[tikz,convert={size=640}]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
legend entries={simulation sample 1,
                measurement sample 1,
                simulation sample 2,
                measurement sample 2},
legend pos=outer north east]
\addplot[mark=o,color=blue] coordinates {
  (0,0)
  (1,1)
  (2,2)
};
\addplot[mark=o,color=green] coordinates {
  (0,1)
  (1,1.5)
  (2,1.8)
};
\addplot[mark=square,color=blue] coordinates {
  (3,0.5)
  (4.5,1)
  (5,2)
};
\addplot[mark=square,color=green] coordinates {
  (3,0)
  (4,1)
  (5,2.2)
};
\end{axis}
\end{tikzpicture}
\end{document}

which produces this image:

enter image description here

But now I want to group my legend entries and only have an entry with line color blue to indicate the simulations and one with line color green for measurements and then one for the circle marker for the sample 1 and one for the square marker to indicate the sample 2. How do I achieve this? Can I insert a ghost plot which is only visible in the entries, or can I use the \addlegendimage command to adjust the legend image?

Best Answer

Here's slightly different version of Martin H's excellent answer that works without the \addlegendentry commands and uses the legend entries key instead (I find that to be more readable). The legend entries are assigned to the \addplot and \addlegendimage commands in the order they're given, so if you move the \addlegendimages before the \addplots (or if you add forget plot to the \addplot options), you can use the legend entries key:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
legend entries={simulation,
                measurement,
                sample 1,
                sample 2},
legend pos=outer north east]
\addlegendimage{no markers,green}
\addlegendimage{no markers,blue}
\addlegendimage{only marks, mark=o}
\addlegendimage{only marks, mark=square}
\addplot[mark=o,color=blue] coordinates {
  (0,0)
  (1,1)
  (2,2)
};
\addplot[mark=o,color=green] coordinates {
  (0,1)
  (1,1.5)
  (2,1.8)
};
\addplot[mark=square,color=blue] coordinates {
  (3,0.5)
  (4.5,1)
  (5,2)
};
\addplot[mark=square,color=green] coordinates {
  (3,0)
  (4,1)
  (5,2.2)
};
\end{axis}
\end{tikzpicture}
\end{document}
Related Question