# Tikz Pgfplots - Create legend from bar chart with Stripes

I have a problem trying to create the legend for my bar chart with stripes.

I would like to create a legend showing rectangles with stripes for each bar, like it is presented in the pic.

The code that creates the above figure is:

\documentclass[11pt,twoside,a4paper]{article}

\usepackage{pgfplots}
\usetikzlibrary{plotmarks}
\usetikzlibrary{arrows.meta}
\usepgfplotslibrary{patchplots}
\usepackage{grffile}
\usetikzlibrary{patterns}

\begin{document}

\begin{tikzpicture}
\scriptsize
\begin{axis}[/pgf/number format/1000 sep={},
width=1.9in,
height=1.5in,
at={(0.6in,0.83in)},
scale only axis,
bar shift auto,
clip=false,
separate axis lines,
every outer x axis line/.append style={black},
every x tick label/.append style={font=\color{black}},
every x tick/.append style={black},
xmin=0,
xmax=4,
xtick={1,2,3},
xticklabels={\empty},
every outer y axis line/.append style={red},
every y tick label/.append style={font=\color{red}},
every y tick/.append style={red},
ymin=0,
ymax=10,
ylabel={YYY},
axis background/.style={fill=white},
legend style={at={(0.03,0.97)}, anchor=north west, legend cell align=left,     align=left, draw=black}
]
postaction={
pattern=north east lines}, draw=black] table[row sep=crcr] {%
1   2\\
2   3\\
3   4\\
};

table[row sep=crcr]{
0   0\\
4   0\\
};

postaction={
pattern=dots}, draw=black] table[row sep=crcr] {
1   2\\
2   3\\
3   4\\
};

postaction={
pattern=horizontal lines}, draw=black] table[row sep=crcr] {
1   2\\
2   3\\
3   4\\
};

\end{axis}
\end{tikzpicture}

\end{document}


Sorry if this question has been posted again, but I couldn't figure out a solution from all the related topics I have seen. Thank you very much in advance.

You can do this by defining your own legend style.

Please have a look at the code for more details. (Please note, that I reduced your code only to the necessary parts here.)

% used PGFPlots v1.14
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{
patterns,
}
\pgfplotsset{
compat=1.7,
% define your own legend style here
my ybar legend/.style={
legend image code/.code={
\draw [##1] (0cm,-0.6ex) rectangle +(2em,1.5ex);
},
},
}
\begin{document}
\begin{tikzpicture}
\scriptsize
\begin{axis}[
width=1.9in,
height=1.5in,
scale only axis,
ymin=0,
enlarge x limits={abs=0.5},
bar shift auto,
legend pos=north west,
table/row sep=crcr,
ybar,
bar width=0.1,
% apply your own legend style here (or at each \addplot command)
my ybar legend,
]
\addplot [pattern=north east lines] table {
1   2\\
2   3\\
3   4\\
};
1   2\\
2   3\\
3   4\\
};
1   2\\
2   3\\
3   4\\
};
\legend{
First,
Second,
Third,
}

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

• thank you very much! This was just what I was looking for! (there were unnecessary parts because matl2tikz create the code) Feb 1 '17 at 21:31