9

With the help of Positioning of Pgfplot axis labels I managed to create histograms of binomial distributions. What I still need is to select some of the bars and fill them with a different color or mark them in another way in order to indicate probabilities like P(X < 4) or P(3 < X < 5).

This is what I've got so far.

\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}
user2395367
  • 350
  • 3
  • 7
  • Related (for the binomial distribution): http://tex.stackexchange.com/questions/198572/tikz-binomial-distribution – Jake Oct 29 '14 at 20:11

1 Answers1

9

You can add another \addplot command with a different samples at={...} key:

\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}
Jake
  • 232,450