18

I am have a similar Grouped Bar Chart as shown in this question and wish to know why there are multiple bars in the legend entry. Is it possible to modify the legend so as to consolidate these bars? Legends with two bars

17

The legend image code for ybar legend is defined as (page 212 chapter 4)

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

It is nothing but a bar plot with two coordinates, so you get two bars. By consolidating, if you mean to have a single bar, you may redefine it like

\pgfplotsset{compat=1.11,
    /pgfplots/ybar legend/.style={
    /pgfplots/legend image code/.code={%
       \draw[##1,/tikz/.cd,yshift=-0.25em]
        (0cm,0cm) rectangle (3pt,0.8em);},
   },
}

to get

enter image description here

or simply remove the second coordinate as in

\draw[##1,/tikz/.cd,bar width=3pt,yshift=-0.2em,bar shift=0pt]
            plot coordinates {(0cm,0.8em)};},

Code:

\documentclass[margin=10pt]{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.11,
        /pgfplots/ybar legend/.style={
        /pgfplots/legend image code/.code={%
        %\draw[##1,/tikz/.cd,yshift=-0.25em]
                %(0cm,0cm) rectangle (3pt,0.8em);},
        \draw[##1,/tikz/.cd,bar width=3pt,yshift=-0.2em,bar shift=0pt]
                plot coordinates {(0cm,0.8em)};},
},
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
x tick label style={
/pgf/number format/1000 sep=},
ylabel=Population,
enlargelimits=0.15,
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=-1},
ybar=5pt,% configures ‘bar shift’
bar width=9pt,
nodes near coords,
point meta=y *10^-7 % the displayed number
]
\addplot
coordinates {(1930,50e6) (1940,33e6)
(1950,40e6) (1960,50e6) (1970,70e6)};
\addplot
coordinates {(1930,38e6) (1940,42e6)
(1950,43e6) (1960,45e6) (1970,65e6)};
\legend{Far,Near}
\end{axis}
\end{tikzpicture}
\end{document}
3

To fix this, just add style area legend after xbar or ybar.

The documentation for it says that it sets:

\pgfplotsset{
    legend image code/.code={
        \draw [#1] (0cm,-0.1cm) rectangle (0.6cm,0.1cm);
    },
}

This is how it looks:

enter image description here

  • 2
    It is recommended to explain with some more detail how such brief answers could be right according to the OP's request and for the benefit of the community. You can improve your answer with codes, images, links and step-by-step explanations. – Cragfelt Nov 22 '17 at 19:39
  • 1
    I don't know why this works, or how it works, but this seemed simpler :) – Nehal J Wani Dec 18 '18 at 4:06

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.