How to plot a multivariate normal distribution?

Just a warning/note about x-y ordering when creating the Z grid: if you’re plotting as a contour/heatmap, then you’ll want to reverse the for x in X, y in Y ordering to be for y in Y, x in X so that the grid maps to the x-y axes correctly. This is subtle, as it will not always present itself as a problem depending on the parameters of the MvNormal.

Here’s an example plotting a bivariate normal distribution as filled contours:

using Distributions
using Plots

μ = [0, 0]
Σ = [1  0.9;
     0.9 10]
p = MvNormal(μ, Σ)

X = range(-8, 8, length=100)
Y = range(-8, 8, length=100)
Z = [pdf(p, [x,y]) for y in Y, x in X] # Note x-y "for" ordering
contourf(X, Y, Z, color=:viridis)

To avoid Z altogether, you can pass a function f to handle calculating the z-values:

f(x,y) = pdf(p, [x,y])
contourf(X, Y, f, color=:viridis)

image

4 Likes