[Tex/LaTex] Bell Curve/Gaussian Function/Normal Distribution in TikZ/PGF

pgfplotsplottikz-pgf

Can anyone tell me how to plot a gaussian function/bell curve using TikZ/PGF? I'm basically looking to implement something like PSTricks's \psGauss command.

Best Answer

You can use pgfplots to plot the functions. There's no standard macro for it, but the function isn't too complicated and can be added as a pgfmath function (based on this answer: How do I use pgfmathdeclarefunction to create define a new pgf function?):

\documentclass{article}
\usepackage{pgfplots}
\begin{document}

\pgfmathdeclarefunction{gauss}{2}{%
  \pgfmathparse{1/(#2*sqrt(2*pi))*exp(-((x-#1)^2)/(2*#2^2))}%
}

\begin{tikzpicture}
\begin{axis}[every axis plot post/.append style={
  mark=none,domain=-2:3,samples=50,smooth}, % All plots: from -2:2, 50 samples, smooth, no marks
  axis x line*=bottom, % no box around the plot, only x and y axis
  axis y line*=left, % the * suppresses the arrow tips
  enlargelimits=upper] % extend the axes a bit to the right and top
  \addplot {gauss(0,0.5)};
  \addplot {gauss(1,0.75)};
\end{axis}
\end{tikzpicture}
\end{document}

pgfplots gauss distribution


In my original answer, I had just declared a normal LaTeX function to the same end:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}

\newcommand\gauss[2]{1/(#2*sqrt(2*pi))*exp(-((x-#1)^2)/(2*#2^2))} % Gauss function, parameters mu and sigma

\begin{tikzpicture}
\begin{axis}[every axis plot post/.append style={
  mark=none,domain=-2:3,samples=50,smooth}, % All plots: from -2:2, 50 samples, smooth, no marks
axis x line*=bottom, % no box around the plot, only x and y axis
axis y line*=left, % the * suppresses the arrow tips
enlargelimits=upper] % extend the axes a bit to the right and top
\addplot {\gauss{0}{0.5}};
\addplot {\gauss{1}{0.75}};
\end{axis}
\end{tikzpicture}
\end{document}