如何使用 numpy 绘制 3D 高斯图?

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

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

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,因为我需要一组数据。

您需要获取正确的尺寸。这可以使用 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()

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

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

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