更改二项分布直方图中各个条形的颜色

更改二项分布直方图中各个条形的颜色

在...的帮助下Pgfplot 轴标签的定位我成功创建了二项分布的直方图。我还需要选择一些条形并用不同的颜色填充它们或以其他方式标记它们,以指示概率,如 P(X < 4) 或 P(3 < X < 5)。

这是我目前所得到的。

\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}[ymin=0, xmin=-0.5,axis lines=left,xlabel={$k$}, ylabel={$P(X=k)$}, x label style={at={(axis description cs:1,0.1)},anchor=north},
    y label style={at={(axis description cs:-0.15,1)},rotate = -90, anchor=north}, ,
    samples at={0,...,12},
    yticklabel style={
        /pgf/number format/fixed,
        /pgf/number format/fixed zerofill,
        /pgf/number format/precision=2
    },
    ybar=0pt, bar width=1
]
\addplot [fill=lightgray, fill opacity=0.5] {binom(x,12,0.4)}; 
\end{axis}
\end{tikzpicture}
\end{document}

答案1

您可以\addplot使用不同的samples at={...}键添加另一个命令:

\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}[ymin=0, xmin=-0.5,axis lines=left,xlabel={$k$}, ylabel={$P(X=k)$}, x label style={at={(axis description cs:1,0.1)},anchor=north},
    y label style={at={(axis description cs:-0.15,1)},rotate = -90, anchor=north}, ,
    samples at={0,...,12},
    yticklabel style={
        /pgf/number format/fixed,
        /pgf/number format/fixed zerofill,
        /pgf/number format/precision=2
    },
    ybar=0pt, bar width=1, bar shift=0pt
]
\addplot [fill=gray!25] {binom(x,12,0.4)}; 
\addplot [fill=orange, samples at={0,...,4}] {binom(x,12,0.4)};
\addplot [fill=cyan, samples at={7}] {binom(x,12,0.4)};
\end{axis}
\end{tikzpicture}
\end{document}

相关内容