在長條圖中的條形新增標籤

在長條圖中的條形新增標籤

我正在嘗試在條形圖中的條形上添加標籤。

我發現 \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}

相關內容