python - Plot normal distribution in 3D -


i trying plot comun distribution of 2 normal distributed variables.

the code below plots 1 normal distributed variable. code plotting 2 normal distributed variables?

import matplotlib.pyplot plt import numpy np import matplotlib.mlab mlab import math  mu = 0 variance = 1 sigma = math.sqrt(variance) x = np.linspace(-3, 3, 100) plt.plot(x,mlab.normpdf(x, mu, sigma))  plt.show() 

it sounds you're looking multivariate normal distribution. implemented in scipy scipy.stats.multivariate_normal. it's important remember passing covariance matrix function. keep things simple keep off diagonal elements zero:

[x variance ,     0    ] [     0     ,y variance] 

here example using function , generating 3d plot of resulting distribution. add colormap make seeing curves easier feel free remove it.

import numpy np import matplotlib.pyplot plt scipy.stats import multivariate_normal mpl_toolkits.mplot3d import axes3d  #parameters set mu_x = 0 variance_x = 3  mu_y = 0 variance_y = 15  #create grid , multivariate normal x = np.linspace(-10,10,500) y = np.linspace(-10,10,500) x, y = np.meshgrid(x,y) pos = np.empty(x.shape + (2,)) pos[:, :, 0] = x; pos[:, :, 1] = y rv = multivariate_normal([mu_x, mu_y], [[variance_x, 0], [0, variance_y]])  #make 3d plot fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(x, y, rv.pdf(pos),cmap='viridis',linewidth=0) ax.set_xlabel('x axis') ax.set_ylabel('y axis') ax.set_zlabel('z axis') plt.show() 

giving plot: enter image description here

edit

a simpler verision avalible through matplotlib.mlab.bivariate_normal takes following arguments don't need worry matrices matplotlib.mlab.bivariate_normal(x, y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0) here x, , y again result of meshgrid using recreate above plot:

import numpy np import matplotlib.pyplot plt matplotlib.mlab import biivariate_normal mpl_toolkits.mplot3d import axes3d  #parameters set mu_x = 0 sigma_x = np.sqrt(3)  mu_y = 0 sigma_y = np.sqrt(15)  #create grid , multivariate normal x = np.linspace(-10,10,500) y = np.linspace(-10,10,500) x, y = np.meshgrid(x,y) z = bivariate_normal(x,y,sigma_x,sigma_y,mu_x,mu_y)  #make 3d plot fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(x, y, z,cmap='viridis',linewidth=0) ax.set_xlabel('x axis') ax.set_ylabel('y axis') ax.set_zlabel('z axis') plt.show() 

giving: enter image description here


Comments