我正在尝试绘制 N 和 p 特定值的二项分布的 pmf。例如,当 N=10 和 p=0.5 时:
\documentclass{article}
\usepackage{amsmath}
\usepackage{pgfplots}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw (0,0) -- (10,0);
\foreach \x in {1,2,...,10} \draw (\x,10!/(\x!*(10-\x!))*(0.5)^\x*(0.5)^(10-\x)) circle (2pt);
\end{tikzpicture}
\end{document}
我本质上看到的是 10 个点的离散图,其中 k 沿 x 轴,概率绘制在 y 轴上。该坐标看起来太复杂了,我猜有更简单的方法来解决这个问题?
答案1
您可以使用 PGFPlots 创建函数图(和数据文件图):
二项式函数未在数学引擎中定义,但你可以使用键自行定义它
declare function={binom(\k,\n,\p)=\n!/(\k!*(\n-\k)!)*\p^\k*(1-\p)^(\n-\k);}
然后你可以使用
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[
declare function={binom(\k,\n,\p)=\n!/(\k!*(\n-\k)!)*\p^\k*(1-\p)^(\n-\k);}
]
\begin{axis}[
samples at={0,...,40},
yticklabel style={
/pgf/number format/fixed,
/pgf/number format/fixed zerofill,
/pgf/number format/precision=1
}
]
\addplot [only marks, cyan] {binom(x,40,0.2)}; \addlegendentry{$p=0.2$}
\addplot [only marks, orange] {binom(x,40,0.5)}; \addlegendentry{$p=0.5$}
\end{axis}
\end{tikzpicture}
\end{document}
要获取直方图,请ybar=0pt, bar width=1
在选项中进行设置(请确保已在序言中axis
设置或更新):\pgfplotsset{compat=1.7}
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.7}
\begin{document}
\begin{tikzpicture}[
declare function={binom(\k,\n,\p)=\n!/(\k!*(\n-\k)!)*\p^\k*(1-\p)^(\n-\k);}
]
\begin{axis}[
samples at={0,...,40},
yticklabel style={
/pgf/number format/fixed,
/pgf/number format/fixed zerofill,
/pgf/number format/precision=1
},
ybar=0pt, bar width=1
]
\addplot [fill=cyan, fill opacity=0.5] {binom(x,40,0.2)}; \addlegendentry{$p=0.2$}
\addplot [fill=orange, fill opacity=0.5] {binom(x,40,0.5)}; \addlegendentry{$p=0.5$}
\end{axis}
\end{tikzpicture}
\end{document}