[Tex/LaTex] How to add legend to contour plots

legendpgfplotstikz-pgf

The following does not work:

\documentclass{standalone}
\usepackage{tikz,pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}[view={0}{90},legend entries={foo,bar}] % 'legend entries' causes compilation error
\addplot3[contour gnuplot={draw color=red,labels=false}]  {x*y};
\addplot3[contour gnuplot={draw color=blue,labels=false}] {x^2 + y^2};
\end{axis}
\end{tikzpicture}
\end{document}

Best Answer

This is a bug (thanks for the report).

A valid work-around might be to reconfigure the legend for this plot:

\documentclass{standalone}
\usepackage{tikz,pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}[view={0}{90},
    legend image post style={
        sharp plot, 
        draw=\pgfkeysvalueof{/pgfplots/contour/draw color},
    },
    legend entries={foo,bar}] % 'legend entries' causes compilation error
\addplot3[contour gnuplot={draw color=red,labels=false}]  {x*y};
\addplot3[contour gnuplot={draw color=blue,labels=false}] {x^2 + y^2};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

The legend image post style means to interprete the coordinates of the current legend style as a normal "sharp plot". The draw statement retrieves the current value of the contour color setting (which matches your use-case here).