pgfplots 中聚集条形图上方的数字

pgfplots 中聚集条形图上方的数字

我想制作一个由两个条形图组成的条形图,就像下面的代码一样。但是,我想要数字居中两个条形上方各有一个数字,而不是每个条形上方都有两个数字。我该怎么做?

MWE(取自 pgfplots 手册):

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\pagestyle{empty}

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

图表

答案1

您还可以pgfplots计算差异:

\documentclass{article}
\usepackage{pgfplots,pgfplotstable}
\pgfplotsset{compat=1.14}

\pgfplotstableread{
x y1 y2
1930 50e6 38e6
1940 33e6 42e6
1950 40e6 43e6
1960 50e6 45e6
1970 70e6 65e6
}\mydata

\begin{document}
\begin{tikzpicture}
\begin{axis}[
    ymin=0,
    x tick label style={
        /pgf/number format/1000 sep=},
    ylabel=Population,
    enlarge x limits=0.15,
    legend style={at={(0.5,-0.15)},
        anchor=north,legend columns=-1},
    ybar=5pt,% configures `bar shift'
    bar width=9pt,
]
\addplot table[x=x,y=y1] {\mydata};
\addplot table[x=x,y=y2] {\mydata};

\addplot [
  only marks,
  point meta=explicit,
  nodes near coords={\pgfmathprintnumber[precision=1,showpos]{\pgfplotspointmeta}\%},
  nodes near coords style={above}
  ]
  table[
    x=x,
    y expr={max(\thisrow{y1},\thisrow{y2})},
    meta expr={(\thisrow{y2}-\thisrow{y1})/\thisrow{y1} * 100}] {\mydata};

\legend{Far,Near}
\end{axis}
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

尝试这个:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\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)};
\addplot[only marks, nodes near coords, point meta=explicit symbolic]
    coordinates { (1930,50e6) [ $-24$ ] (1940,42e6) [ $+27$ ] (1950,43e6) [ $+7.5$ ]
    (1960,50e6) [ $-10$ ] (1970,70e6) [ $-7$ ] }; 

\legend{Far,Near}
\end{axis}
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容