Reputation:
I am trying to plot a Gaussian distribution via matplotlib, but all I get back is an empty figure:
When I searched the internet, I understood that three arguments are required for the ax.plot_surface()
function, the X values, Y values, and Z (a function that calculates Z from X, Y). Is this correct?
I post the code below in hope you can help me figuring out what I am doing wrong here. Thanks!
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
###############################################
### The multivariate Gaussian density function
###############################################
def pdf_multivariate_gauss(x, mu, cov):
'''
Caculate the multivariate normal density (pdf)
Keyword arguments:
x = numpy array of a "d x 1" sample vector
mu = numpy array of a "d x 1" mean vector
cov = "numpy array of a d x d" covariance matrix
'''
assert(mu.shape[0] > mu.shape[1]), 'mu must be a row vector'
assert(x.shape[0] > x.shape[1]), 'x must be a row vector'
assert(cov.shape[0] == cov.shape[1]), 'covariance matrix must be square'
assert(mu.shape[0] == cov.shape[0]), 'cov_mat and mu_vec must have the same dimensions'
assert(mu.shape[0] == x.shape[0]), 'mu and x must have the same dimensions'
part1 = 1 / ( ((2* np.pi)**(len(mu)/2)) * (np.linalg.det(cov)**(1/2)) )
part2 = (-1/2) * ((x-mu).T.dot(np.linalg.inv(cov))).dot((x-mu))
return float(part1 * np.exp(part2))
# Test
x = np.array([[0],[0]])
mu = np.array([[0],[0]])
cov = np.eye(2)
print(pdf_multivariate_gauss(x, mu, cov))
#prints 0.15915494309189535
###############################################
### The plot
###############################################
mu = np.array([[0],[0]])
cov = np.eye(2)
def construct_Z(X, Y, mu, cov):
Z = []
for i,j in zip(X,Y):
x = np.array([i,j]).reshape(2,1)
Z.append(pdf_multivariate_gauss(x, mu, cov))
return Z
X = linspace(-5, 5, 200)
Y = linspace(-5, 5, 200)
Z = construct_Z(X, Y, mu, cov)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, color='0.8',
alpha=0.85, linewidth=1)
plt.show()
Upvotes: 2
Views: 4664
Reputation: 1236
I'm no expert with 3D-plots in matplotlib, but I believe your data wrong.
As you can see in the sourcecode in this tutorial, your X,Y
and Z
data have to be 2-dimensional arrays. Your X
and Y
are one-dimensional, and your Z is a simple list.
Try reshaping your data to a grid, maybe using X, Y = np.meshgrid(X, Y)
Upvotes: 2