我想绘制多个实验的直方图,其中可能事件是 1 到 10 之间的数字。由于实验的抽取次数不同,因此直方图应显示标准化为 100 次抽取的每个实验。
为了便于输入,此规范化应由宏执行\expandrow
,该宏将总绘制次数和一个数字列表作为参数,该列表指定观察到特定事件的频率。例如,\expandrow{31}{5,4,1,9,2,8,0,0,2}
= (1, 16.12854) (2, 12.90283) (3, 3.22571) (4, 29.03137) (5, 6.45142) (6, 25.80566) (7, 0.0) (8, 0.0) (9, 6.45142)
。宏可以独立运行,但如果在\addplot
命令中应用则不起作用。我该如何解决这个问题?
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\newcommand{\expandrow}[2]{
\foreach \v [count = \i] in {#2} {
(\i, \pgfmathparse{\v/#1 * 100}\pgfmathresult)
}
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
enlarge y limits={abs=2em},
bar width = {.4em},
enlargelimits=0.15,
ylabel={percentage},
symbolic x coords={1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=-1},
nodes near coords = {\tiny \pgfmathprintnumber\pgfplotspointmeta},
nodes near coords align={vertical},
]
% A
% \addplot coordinates {\expandrow{31}{5,4,1,9,2,8,0,0,2}};
\addplot coordinates {
(1, 16.12854) (2, 12.90283) (3, 3.22571) (4, 29.03137) (5, 6.45142) (6, 25.80566) (7, 0.0) (8, 0.0) (9, 6.45142)
};
% B
% \addplot coordinates {\expandrow{1739}{157,1285,246,47,4}};
\addplot coordinates {
(1, 9.0271) (2, 73.89221) (3, 14.1449) (4, 2.70233) (5, 0.22888)
};
\legend{A, B}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
如果执行额外的步骤,并首先将规范化的坐标列表存储在宏中,那么您可以执行类似以下代码的操作,我借用了 egreg 对 是否可以存储由 foreach 生成的数组?
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\makeatletter
\newcommand\normalize[3]{%
\gdef\store@temp{}%
\foreach [count=\i] \v in {#2}{\pgfmathparse{\v/#1 * 100}\xdef\store@temp{\store@temp (\i,\pgfmathresult)}}%
\let#3=\store@temp
}
\makeatother
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
enlarge y limits={abs=2em},
bar width = {.4em},
enlargelimits=0.15,
ylabel={percentage},
symbolic x coords={1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=-1},
nodes near coords = {\tiny \pgfmathprintnumber\pgfplotspointmeta},
nodes near coords align={vertical},
]
% do the normalization
\normalize{31}{5,4,1,9,2,8,0,0,2}{\rowA}
\normalize{1739}{157,1285,246,47,4}{\rowB}
% plot the data
% A
\addplot coordinates {\rowA};
% B
\addplot coordinates {\rowB};
\legend{A, B}
\end{axis}
\end{tikzpicture}
\end{document}