这是我当前必须生成以下直方图的代码:
\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 手册,第 4 章,第 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}