为条形图中的条形添加标签

为条形图中的条形添加标签

我正在尝试在条形图的条形上添加标签。

我找到了 \node [above] at (axis cs: 1, 810) {$Q1$};,但这个位于两个条形图的中间。我希望 y 轴的值浮动在条形图的顶部(或者可能在条形图内部)

我的 MWE 看起来像这样,没有标签就不太具有表现力。有什么建议吗?

  \documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
    \begin{axis}[
        ybar,
        width  = 12cm,
        height = 5cm,
        bar width=20pt,
        ylabel={number of participants},
        symbolic x coords={High School, Bachelor degree, Master degree, Ph.D or similar},
        xtick = data,
    ]
    \addplot[fill=blue] coordinates {(High School, 1) (Bachelor degree, 2) (Master degree, 3) (Ph.D or similar, 4)};
     \addplot[fill=red] coordinates {(High School, 3) (Bachelor degree, 2) (Master degree, 8) (Ph.D or similar, 4)};
      \legend{Native speaker, Non-native speaker}
    \end{axis}
\end{tikzpicture}
\caption{Participants: Level of education}
\label{participantsLanguageOverviewNonNative}
\end{figure}
\end{document}

答案1

nodes near coords的作用正是如此,因此将其添加到axis选项中,您就快完成了。您还需要稍微拉伸轴,因为现在没有足够的空间放置标签,因此enlarge y limits={value=0.2,upper}也添加。我还会设置ymin=0。最后,使用移动图例legend pos=north west,这样它就不会遮住条形图。

如果您想要条形内的标签,请添加nodes near coords align=below,这种情况下您不需要enlarge y limits

在此处输入图片描述

\documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
    \begin{axis}[
        ybar,
        ymin=0,
        width=12cm,
        height=5cm,
        bar width=20pt,
        ylabel={number of participants},
        nodes near coords,
 %      nodes near coords align=below, % places labels inside bars
        symbolic x coords={High School, Bachelor degree, Master degree, Ph.D or similar},
        xtick = data,
        enlarge y limits={value=0.2,upper},
        legend pos=north west
    ]
    \addplot[fill=blue] coordinates {(High School, 1) (Bachelor degree, 2) (Master degree, 3) (Ph.D or similar, 4)};
     \addplot[fill=red] coordinates {(High School, 3) (Bachelor degree, 2) (Master degree, 8) (Ph.D or similar, 4)};
      \legend{Native speaker, Non-native speaker}
    \end{axis}
\end{tikzpicture}
\caption{Participants: Level of education}
\label{participantsLanguageOverviewNonNative}
\end{figure}
\end{document}

相关内容