7

I'm trying to use the result from a fill between as a legend entry, but I can't get it to work:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}

\usepgfplotslibrary{fillbetween}

\begin{document}

\begin{figure}
    \begin{tikzpicture}
        \begin{axis}
            \addplot[name path = upper, draw = none] {5 + rand};
            \addplot[name path = lower, draw = none] {-5 + rand};
            \addplot[black!10, area legend] fill between[of = upper and lower];
            \addlegendentry{My interval}
        \end{axis}
    \end{tikzpicture}
\end{figure}

\end{document}

gives

enter image description here

with a line in the legend image instead of the rectangle I expected from using area legend in the options to \addplot.

I tried providing a legend image manually using

\addlegendimage{\draw[fill = black!10] (0cm, -0.1cm) rectangle (0.6cm, 0.1cm)}

but that did nothing. (The \draw code is inspired by Section 4.9.5 in the pgfplots manual and is supposed to be the default appearance of a area legend entry.)

Any ideas? Thanks in advance.

Edit:

Adding area legend to the axis option gets me halfway there, but the fill is still not right.

enter image description here

  • You've got me baffled. The pgfplots manual shows an example of this "just working" on p. 382 (v1.12) with no special handling. – Paul Gessler May 23 '15 at 21:17
  • 2
    The first \addlegendentry refers to the first \addplot, the second \addlegendentry refers to the second \addplot, and so on. It doesn't matter where they are relative to each other. – John Kormylo May 24 '15 at 17:15
4

The comment by John Kormylo put me on the right track. The key is to make the legend refer to the third plot only by issuing forget plot to the two previous ones. The following works:

\begin{axis}
    \addplot[name path = upper, draw = none, forget plot] {5 + rand};
    \addplot[name path = lower, draw = none, forget plot] {-5 + rand};
    \addplot[fill = black!10, area legend] fill between[of = upper and lower];
    \addlegendentry{My interval}
\end{axis}

enter image description here

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.