[Tex/LaTex] Pgfplot: create own marker or fill marker with pattern (legend)

pgfplotstikz-pgf

I have a hatched area and would like to create a marker with same hatched filling for the legend. But it seems like even setting just a marker doesn't work — what's going wrong? And it would be greatif some could explain me how to fill the marker with a hatching/pattern.

\documentclass[border=4pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{
compat=1.12
}
\usetikzlibrary{patterns}


\begin{document}
\begin{tikzpicture}
\begin{axis}[
      legend style={cells={align=left}}
   ]  
    \addplot {rnd};
\addlegendentry{a};

\addplot [ draw=none, postaction={pattern = north east lines, pattern color=red}] coordinates {
    (0, 1)
    (0, 0)
    (2, 0)
    (2, 1)
};

\addlegendimage{red, mark=square}%pattern = north east lines, pattern color=red
\addlegendentry{b};

\end{axis}
\end{tikzpicture}
\end{document} 

enter image description here

Best Answer

The \addplot command defines already a legend image that is used for the second legend entry (b). Add area legend to the options of this plot to get a square filled with the pattern instead the default line legend image.

Note that there will be a black border because the original area legend style uses a \draw command. To remove this border you can add legend image post style={draw opacity=0} to the plot options.

enter image description here

\documentclass[border=4pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{
    compat=1.12
}
\usetikzlibrary{patterns}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
      legend style={cells={align=left}}
   ]  
    \addplot {rnd};
\addlegendentry{a};

\addplot [draw=none,pattern = north east lines, pattern color=red,
    area legend,
    legend image post style={draw opacity=0}% if the border of the legend image should be removed
] coordinates {
    (0, 1)
    (0, 0)
    (2, 0)
    (2, 1)
};
\addlegendentry{b};

\end{axis}
\end{tikzpicture}
\end{document}

Or you define a new style for the legend image using \path instead \draw.

\documentclass[border=4pt]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{patterns}
\pgfplotsset{
    compat=1.12,
    my area legend/.style={
        legend image code/.code={%
            \path[#1](0cm,-.1cm)rectangle(.6cm,.1cm);% \path instead \draw
        }
    }
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
      legend style={cells={align=left}},
   ]  
    \addplot {rnd};
\addlegendentry{a};

\addplot[draw=none,pattern = north east lines, pattern color=red,
    my area legend
    ] coordinates {
    (0, 1)
    (0, 0)
    (2, 0)
    (2, 1)
};
\addlegendentry{b};

\end{axis}
\end{tikzpicture}
\end{document}