[Tex/LaTex] Plotting a Bivariate Normal Distribution in Tikz

pgfplotstikz-pgf

I have been trying to make a 3D plot of a certain bivariate normal distribution but that is far from ideal at the moment. The code I have been using is

\begin{tikzpicture}
\centering
\begin{axis}[
width=6in,
height=4in,
title=Bivariate Normal Distribution,
axis lines=left,
grid=both,
]
\addplot3[samples=50,surf,faceted color=blue]
{1/(2 *pi* sqrt(1-0.9^2))* exp(-(x^2+y^2-2*0.9*x*y)/(2*(1-0.9^2))};
\end{axis}
\end{tikzpicture}

which produces this

enter image description here

This is is not what I would like though and me messing with the different graphical parameters of \addplot3 does not lead to a more pleasant result for the eyes. Ideally, the surface I would like to produce is something like this

enter image description here

I really don't mind the shape, I can change it without any problems, it's the graphics I am having trouble with. Could you please tell me which parameters I need to change to get something like the picture above?

Thank you.

Best Answer

The main difference between the image of the 3rd party tool and pgfplots is that you have a considerably more involved example for pgfplots: the sampling density is way too low to draw a rotated asymmetric distribution in cartesian coordinates.

Options include:

  1. do not use a rotated distribution if it does not matter anyway. Solutions how to do it are shown in all detail in Draw a bivariate normal distribution in TikZ, in this case it is a duplicate.
  2. maybe polar coordinates are better suited (I did not try it)
  3. increase the sampling density

Here is what comes out of approach (3):

\documentclass{standalone}

\usepackage{pgfplots}

\pgfplotsset{compat=1.12}


\begin{document}

\begin{tikzpicture}
\begin{axis}[
width=6in,
height=4in,
title=Bivariate Normal Distribution,
axis lines=left,
grid=both,
]
\addplot3[samples=150,surf,shader=interp]
{1/(2 *pi* sqrt(1-0.9^2))* exp(-(x^2+y^2-2*0.9*x*y)/(2*(1-0.9^2)))};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

I made some obvious and some non-obvious changes to your code and I would like to discuss them here:

  1. \centering inside of a tikzpicture has no effect.
  2. I added compat=1.12 and compiled the picture with lualatex. This is much faster than any older compat level or pdflatex.
  3. I fixed a syntax error in your math expression: the last ')' is missing (causing the lua backend to bail out and fall back to the slow TeX implementation which lives with the syntax error).
  4. I used shader=interp since samples=150 results in too many grid lines when used with faceted.