【问题标题】:How to do a 3D plot of gaussian using numpy?如何使用 numpy 绘制 3D 高斯图?
【发布时间】:2019-03-10 06:14:11
【问题描述】:

我正在尝试使用 numpy 绘制一个高斯函数。 函数是 z=exp(-(x2+y2)/10) 但我只得到一个 2D 函数

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)

我得到:

但我想获取:

我正在使用 numpy,因为我需要一组数据。

【问题讨论】:

    标签: python numpy plot gaussian normal-distribution


    【解决方案1】:

    您需要获得正确的尺寸。这可以使用meshgrid 来完成。此外,您想要的图是曲面图,而不是线框(尽管您也可以这样做)。

    # 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()
    

    【讨论】:

    • z = np.exp(-0.1*x**2-0.1*y**2)。使用这个,我相信你也可以避免reshape
    【解决方案2】:

    鉴于高斯分布的原始公式,我编写了以下代码:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from mpl_toolkits.mplot3d import Axes3D # <--- This is important for 3d plotting 
    A = 1
    x0 = 0
    y0 = 0
    
    sigma_X = 2
    sigma_Y = 2
    
    xg = np.linspace(-5,5,num=100)
    yg = np.linspace(-5,5,num=100)
    
    theta= np.pi
    
    X, Y = np.meshgrid(xg,yg)
    
    a = np.cos(theta)**2/(2*sigma_X**2) + np.sin(theta)**2/(2*sigma_Y**2);
    b = -np.sin(2*theta)/(4*sigma_X**2) + np.sin(2*theta)/(4*sigma_Y**2);
    c = np.sin(theta)**2/(2*sigma_X**2) + np.cos(theta)**2/(2*sigma_Y**2);
    
    aXXdet = np.array([a*(Xi-x0)**2 for Xi in X],float)
    bbXYdet = np.array([2*b*(Xi-x0)*(Y[ii]-y0) for ii,Xi in enumerate(X)],float)
    cYYdet = np.array([c*(Yi-y0)**2 for Yi in Y],float)
    Z = np.array([A*np.exp( - (ai + bbXYdet[i] + cYYdet[i])) for i,ai in enumerate(aXXdet)],float);
    
    # plot
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(X, Y, Z, cmap=cm.coolwarm)
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    plt.show()
    

    它还绘制了分布。所以你可以玩弄这些参数,看看它们的效果!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多