1

How to plot bivariate Gaussian density function in Numpy and Matplotlib using a given mean and covariance matrix? It could be a surface or contour plot. I want a generic solution using mean vector and covariance matrix which doesn't involve individual Sigmas.

mean, cov, n_samples = np.array([0.,0.]), np.array([[1.0,0.5],[0.5,1.0]]), 100

Thanks,

@Aso.agile

Aso Agile
  • 417
  • 1
  • 6
  • 13
  • there is some bits in: http://stackoverflow.com/questions/2369492/generate-a-heatmap-in-matplotlib-using-a-scatter-data-set – Aso Agile Dec 07 '12 at 14:24
  • 1
    OK, Wiki has a formula for the density, matplotlib gallery has an example of plotting, what is your question specifically? – ev-br Dec 07 '12 at 14:29
  • One solution would be using mlab and individual sigmas, i.e.: 'code' matplotlib.mlab.bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0). @Aso.agile – Aso Agile Dec 07 '12 at 14:34
  • 1
    Nothing personal, but I don't see an appropriate level of attempt from your side. At this stage, voting to close. – ev-br Dec 07 '12 at 14:39
  • @Zhenya, see my attempt below, then let me have your comment. – Aso Agile Dec 10 '12 at 11:42
  • for starters, what you show has a bunch of syntax errors. – ev-br Dec 10 '12 at 19:15

1 Answers1

1

Here is my try:

import umpy as np
import matplotlib.pyplot as plt 
mean, cov, n_samples = np.array([0.,0.]), np.array([[1.0,0.5],[0.5,1.0]]), 100
data=np.random.multivariate_normal(mean,cov,size=n_samples)
pdf = np.zeros(data.shape[0])
cons = 1./((2*np.pi)**(data.shape[1]/2.)*np.linalg.det(cov)**(-0.5))
X, Y = np.meshgrid(data.T[0], data.T[1])
def pdf(point):
  return cons*np.exp(-np.dot(np.dot((point-mean),np.linalg.inv(cov)),(point-mean).T)/2.)
zs = np.array([pdf(np.array(ponit)) for ponit in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
fig = plt.figure()
ax3D = fig.add_subplot(111, projection='3d')
surf = ax3D.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0, antialiased=Fals)
surf.show()

3D surface plot shows the result but it is a bit bizarre!. Any comment or other solutions are appreciated.

What I expect (and want) is something similar to follow:enter image description here

Aso Agile
  • 417
  • 1
  • 6
  • 13