Trung
Trung

Reputation: 3

Visualizing a multivariate normal distribution in 3D with python

Does anyone know how to make a pretty visualization of the PDF of multivariate (bivariate for simply) normal distribution, with each variable's distribution is projected, like the below figure? Thanks in advance.

Source of the figure: A 3D plot from this thesis.

Upvotes: 0

Views: 3077

Answers (2)

Andrea
Andrea

Reputation: 123

try this script

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

def gauss1(x):
    return np.exp(-(x**2))

def gauss(x, y):
    return gauss1(x)*gauss1(2*y)

fig = plt.figure()
ax = fig.gca(projection='3d')
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = gauss(X, Y)

ax.plot_surface(X, Y, Z, rstride=2, cstride=2, alpha=0.4, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='x', offset=-4, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='y', offset=4, cmap=cm.coolwarm)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

This produces the following result

enter image description here

I am not sure how to plot only the contour lines for the projections, but this should get you started.

Upvotes: 0

Erik André
Erik André

Reputation: 538

This plot is almost certainly produced using matplotlib. Take a look at their tutorials. Stack Overflow also has a matplotlib tag.

To plot in 3D you need to use the mplot3d toolkit.

Upvotes: 1

Related Questions