在直方圖中的條形新增標籤

在直方圖中的條形新增標籤

這是我目前必須產生以下直方圖的程式碼:

\documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}

\begin{axis}[
    ybar,
    ymin=0,
    xlabel={Classes},
    ylabel={Frequency},
    width=10cm,
    height=6cm,
    xtick=data,
    xticklabels={A, B, C, D}, % Add more labels as needed
    enlarge x limits=0.15,
    nodes near coords, % Add labels above each bar
    nodes near coords align={vertical},
    nodes near coords style={font=\tiny},
    ]
    ]
    
    \addplot[fill=blue!30] coordinates {(1, 15) (2, 12) (3, 8) (4, 10) };

    \addplot[fill=green!30] coordinates {(1, 14) (2, 11) (3, 13) (4, 9) };

\end{axis}
\end{tikzpicture}
\end{document}

在此輸入影像描述

我希望圖形看起來像這樣,而不是排名位於條形頂部。 在此輸入影像描述

答案1

好的,這是一種方法。按鍵:

  • 添加point meta=explicit symbolic到每個\addplot
  • 在每個座標後添加所需的值/文本[ ]

請參閱 pgfplots 手冊,第 1 章。 4,p。 114,版本 1.18.1 以了解詳細資訊。

結果

%\documentclass{article}
\documentclass[10pt,border=3mm,tikz]{standalone}    % nicer for development
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}

\begin{axis}[
    ybar,
    ymin=0,
    xlabel={Classes},
    ylabel={Frequency},
    width=10cm,
    height=6cm,
    xtick=data,
    xticklabels={A, B, C, D}, % Add more labels as needed
    enlarge x limits=0.15,
    nodes near coords, % Add labels above each bar
    nodes near coords align={vertical},
    nodes near coords style={font=\tiny},
    ]
    ]
    
    \addplot[fill=blue!30,
             point meta=explicit symbolic
    ] coordinates {
        (1, 15) [1]
        (2, 12) [2]
        (3, 8)  [4]
        (4, 10) [3]
    };

    \addplot[fill=green!30,
             point meta=explicit symbolic
    ] coordinates {
        (1, 14) [1]
        (2, 11) [3]
        (3, 13) [2]
        (4, 9)  [4]
        };

\end{axis}
\end{tikzpicture}
\end{document}

相關內容