# Custom area legend image not working

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];
\end{axis}
\end{tikzpicture}
\end{figure}

\end{document}


gives

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.)

Edit:

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

• 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
• 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

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}
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.6342543363571167, "perplexity": 2394.186196727859}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2020-10/segments/1581875145533.1/warc/CC-MAIN-20200221142006-20200221172006-00203.warc.gz"}