14

I want to draw gamma distribution with different shape and scale parameters. The following MWE displayed error. The error information is : enter image description here

Here is MWE:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\begin{document}

\pgfmathdeclarefunction{gammaPDF}{2}{
\pgfmathparse{1/(#2^#1*gamma(#1))*x^(#1-1)*exp(-x/#2)}
}

\begin{tikzpicture}
\begin{axis}[
width=4cm, 
height=3cm,
axis x line=bottom,
axis y line=left
]
\addplot[
blue!50!white,
mark=none,
domain=0:20, 
samples=100, 
smooth] {\gammaPDF(9,0.5)};
\end{axis}
\end{tikzpicture}
Jake
  • 232,450
user22986
  • 1,421
  • 5
    remove the backslash from gammaPDF and define gamma – percusse Jun 21 '13 at 19:38
  • @percusse: From the link:http://tex.stackexchange.com/questions/80345/student-t-distribution-with-tikz, where the gamma function is used but no predefined. So why I can't use it directly here. – user22986 Jun 21 '13 at 20:07
  • 1
    @user22986: In the answer you linked to, the function is evaluated using the gnuplot backend. The gamma function isn't defined in the PGF math parser. – Jake Jun 21 '13 at 20:21

1 Answers1

24

Here's the gamma PDF using the gamma function approximation that Wolfram Alpha spits out:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\begin{document}



\begin{tikzpicture}[
    declare function={gamma(\z)=
    (2.506628274631*sqrt(1/\z) + 0.20888568*(1/\z)^(1.5) + 0.00870357*(1/\z)^(2.5) - (174.2106599*(1/\z)^(3.5))/25920 - (715.6423511*(1/\z)^(4.5))/1244160)*exp((-ln(1/\z)-1)*\z);},
    declare function={gammapdf(\x,\k,\theta) = \x^(\k-1)*exp(-\x/\theta) / (\theta^\k*gamma(\k));}
]

\begin{axis}[
    axis lines=left,
    enlargelimits=upper,
    samples=50,
    legend entries={$k=1\quad \theta=2$,$k=2\quad \theta=2$, $k=9\quad \theta=0.5$}
]
\addplot [smooth, domain=0:20] {gammapdf(x,1,2)};
\addplot [smooth, domain=0:20, red] {gammapdf(x,2,2)};
\addplot [smooth, domain=0:20, blue] {gammapdf(x,9,0.5)};
\end{axis}
\end{tikzpicture}
\end{document}
didou
  • 193
Jake
  • 232,450
  • 3
    I came here looking for a way to draw the Gamma function itself. It turns out that the approximation is good only for "large z", where large means z > 0.4 or so. For very small z, the approximation even becomes negative. So if you need parameters z < 0.4 for the gamma pdf, another approximation is needed. One way to go is to use the functional equation of the gamma function as follows: Denote the Wolfram alpha approximation of gamma by gammas. Then, instead of working with gammas(z), one can approximate gamma(z) by 1/z * gammas(z+1). – jarauh Oct 15 '15 at 17:26