[Tex/LaTex] Legend marker in pgfplot bar chart

legendpgfplots

I spent the last hours trying to solve this issue. I hope you can help me, sorry if the answer appears clearly somewhere else, I was not able to find it.

I would like to adjust the marker/symbol in the legend for the first plot. I tried with the following (making them green and blue):

\documentclass[12pt]{article}
\usepackage{pgfplots}
\begin{document}

\begin{tikzpicture}
\pgfplotstableread{ % Read the data into a table macro
Label   First Second   
1    5      56.1    
2     22        56.5    
3     5         44.3   
4    5  42.0   
}\datatablet
\begin{axis}[
xbar,
]
\addplot [fill=black]           table [y=Label, x=First] {\datatablet};  
\addplot [fill=black!20!white]  table  [y=Label, x=Second]  {\datatablet}; 
\addlegendimage{area legend,fill=green}\addlegendentry{TEST}  
\addlegendimage{area legend, fill=blue} \addlegendentry{TEST2}
    \end{axis}
\end{tikzpicture}

    \end{document}

which gives me thefollowing output..

enter image description here
what am I doing wrong?
Thanks for your help, Ilkay.

Best Answer

I can't understand why do you want the legend to be of a different colour (it goes against the utility of a legend) but anyway the answer is to define your own styles with the colours already included in this way as in the following. The code is taken from the pgfplots manual from the default definition of the xbar legend style (last part of Legend Appearance section), I have only add the colour definition.

\documentclass[12pt]{article}
\usepackage{pgfplots}
\begin{document}

\pgfplotsset{
    xbar legend green/.style={
        /pgfplots/legend image code/.code={%
            \draw[/tikz/.cd,bar width=3pt,yshift=-0.2em,bar shift=0pt,fill=green] plot coordinates {(0cm,0.8em) (2*\pgfplotbarwidth,0.6em)};
        },
    },
    xbar legend blue/.style={
        /pgfplots/legend image code/.code={%
            \draw[/tikz/.cd,bar width=3pt,yshift=-0.2em,bar shift=0pt,fill=blue] plot coordinates {(0cm,0.8em) 2*\pgfplotbarwidth,0.6em)};
        },
    }
}

\begin{tikzpicture}
\pgfplotstableread{ % Read the data into a table macro
Label   First Second   
1    5      56.1    
2     22        56.5    
3     5         44.3   
4    5  42.0   
}\datatablet
\begin{axis}[
xbar,
]
\addplot [fill=black,xbar legend green]           table [y=Label, x=First] {\datatablet};   
\addplot [fill=black!20!white,xbar legend blue]  table  [y=Label, x=Second]  {\datatablet};
\legend{test,test2}
\end{axis}
\end{tikzpicture}

\end{document}

enter image description here

Related Question