7

I am trying to draw both a line plot and a bar plot in the same plot. However, the legend for the line plot looks wrong.

Question: How do I make the legend look like the legend for a regular line plot?

\documentclass[margin=2mm]{standalone}

\usepackage{pgfplots}

\pgfplotsset{compat=newest}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
      ybar,
      ylabel=Inventory,
      xmin=0,
      xmax=47,
      height=4cm,
      width=\textwidth,
      ymin=0,
      xtick={0,4,8,12,16,20,24,28,32,36,40,44},
      xticklabels={Jul,Aug,Sep,Oct,Nov,Dec,Jan,Feb,Mar,Apr,May,Jun},
      legend style={at={(0.5,-0.33)},anchor=north},
      legend columns=4]
    \addplot[sharp plot,black,very thick] coordinates
        {(0, 100) (1, 90) (2,80) (3,70)
         (4,160) (5,150) (6,140) (7,130)
         (8,120) (9,110) (10,100) (12,90)};
    \addplot[bar width=4pt,draw=purple,fill=purple] coordinates
        {(0, 100) (4,0) (8,0) (12,80)};
    \legend{Inventory, Shipments};
  \end{axis}
\end{tikzpicture}
\end{document}

enter image description here

6

You just need to add the line legend option to that \addplot command:

Sample output

\documentclass{article}

\usepackage{pgfplots}

\pgfplotsset{compat=newest}

\begin{document}

\begin{tikzpicture}
  \begin{axis}[
      ybar,
      ylabel=Inventory,
      xmin=0,
      xmax=47,
      height=4cm,
      width=\textwidth,
      ymin=0,
      xtick={0,4,8,12,16,20,24,28,32,36,40,44},
      xticklabels={Jul,Aug,Sep,Oct,Nov,Dec,Jan,Feb,Mar,Apr,May,Jun},
      legend style={at={(0.5,-0.33)},anchor=north},
      legend columns=4]
    \addplot[line legend,sharp plot,black,very thick] coordinates
        {(0, 100) (1, 90) (2,80) (3,70)
         (4,160) (5,150) (6,140) (7,130)
         (8,120) (9,110) (10,100) (12,90)};
    \addplot[bar width=4pt,draw=purple,fill=purple] coordinates
        {(0, 100) (4,0) (8,0) (12,80)};
    \legend{Inventory,Shipments};
  \end{axis}
\end{tikzpicture}

\end{document}

An alternative way to do this would be to remove the ybar option from the axis options, and write the second \addplot as

\addplot[ybar,ybar legend,....]{...}

See section 4.9.5 of the pgfplots manual for more such options.

|improve this answer|||||
  • Excellent! Thanks for letting me know about the options line legend and ybar legend which are new to me. – I Like to Code Jan 11 '14 at 19:56

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.