Search code examples
pythonnumpyplotgaussiannormal-distribution

How to do a 3D plot of gaussian using numpy?


I'm trying to plot a gaussian function using numpy. the funtion is z=exp(-(x2+y2)/10) but I only get a 2D function

import numpy as np 
from matplotlib import pyplot as plt

x=np.linspace(-10,10, num=100)
y=np.linspace(-10,10, num=100)
z=np.exp(-0.1*x**2-0.1*y**2)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(x,y,z)

I obtain: only obtain 2D gaussian [1]

but I want to obtain: obtained a 3D gaussian but using sympy[2]

I'm using numpy becouse I need the set of data.


Solution

  • You need to obtain the correct dimensions. This can be done using meshgrid. Also, your desired plot is a surface plot, not a wireframe (though you can do that too).

    # import for colormaps
    from matplotlib import cm
    
    x=np.linspace(-10,10, num=100)
    y=np.linspace(-10,10, num=100)
    
    x, y = np.meshgrid(x, y)
    
    z = np.exp(-0.1*x**2-0.1*y**2)
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(x,y,z, cmap=cm.jet)
    plt.show()
    

    enter image description here