pgfplots 中的联合线和条形图的图例看起来很奇怪

pgfplots 中的联合线和条形图的图例看起来很奇怪

我试图在同一个图中绘制线图和条形图。但是,线图的图例看起来不对。

问题: 如何使图例看起来像常规线图的图例?

\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}

在此处输入图片描述

答案1

line legend您只需向该\addplot命令添加选项:

示例输出

\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}

另一种方法是从选项ybar中删除该选项axis,然后将第二个选项写\addplot

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

pgfplots有关更多此类选项,请参阅手册第 4.9.5 节。

相关内容