gpt4 book ai didi

python - 在 3D 绘图 python 中的平面上绘制一维高斯分布

转载 作者:太空宇宙 更新时间:2023-11-03 15:31:29 26 4
gpt4 key购买 nike

我有以下代码和它生成的图。我的目标是在第二个图(右)上绘制所示红色平面上的一维高斯分布。

这样做的目的是表明重叠(代表条件)是高斯分布。我对分布的确切方差是否正确不感兴趣,而只是直观地显示它。

在 python 中有没有直接的方法来做到这一点?

谢谢你

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import bivariate_normal
from mpl_toolkits.mplot3d import Axes3D

#Make a 3D plot
fig = plt.figure(figsize=plt.figaspect(0.5))

################ First Plot ##############
#Parameters to set
mu_x = 0
sigma_x = np.sqrt(5)

mu_y = 0
sigma_y = np.sqrt(5)

#Create grid and 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)

# Create plane
x_p = 2
y_p = np.linspace(-10,10,500)
z_p = np.linspace(0,0.02,500)
Y_p, Z_p = np.meshgrid(y_p, z_p)


# ax = fig.gca(projection='3d')
ax = fig.add_subplot(1,2,1, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis',linewidth=0)
ax.plot_surface(x_p, Y_p, Z_p, color='r',linewidth=0, alpha=0.5)
plt.tight_layout()

################ Second Plot ##############
x_p = 2
y_p = np.linspace(-10,10,500)
z_p = np.linspace(0,0.02,500)
Y_p, Z_p = np.meshgrid(y_p, z_p)


# ax2 = fig.gca(projection='3d')
ax2 = fig.add_subplot(1,2,2,projection='3d')
ax2.plot_surface(x_p, Y_p, Z_p, color='r',linewidth=0, alpha=0.3)
plt.show()

Code output

最佳答案

您可以尝试获取 X 在公差 tol 范围内最接近计划 x_p = 2 的坐标,例如 np.where,然后使用生成的索引 idx_x_p 作为掩码以选择相应的 YZ 值。这将引导您进入以下代码:


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import bivariate_normal
from mpl_toolkits.mplot3d import Axes3D

#Parameters to set for Gaussian distribution
mu_x = 0
sigma_x = np.sqrt(5)
mu_y = 0
sigma_y = np.sqrt(5)

#Create grid and 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)

# Create plane
x_p = 2
y_p = np.linspace(-10,10,500)
z_p = np.linspace(0,0.02,500)
Y_p, Z_p = np.meshgrid(y_p, z_p)

# Finding closest idx values of X mesh to x_p
tol = 1e-4
idx_x_p = (np.where(x < x_p+tol) and np.where(x > x_p-tol))[0][0]
# Select the corresponding values of X, Y, Z (carefully switch X and Y)
x_c, y_c, z_c = Y[idx_x_p], X[idx_x_p], Z[idx_x_p]

# Plot
fig = plt.figure(figsize=plt.figaspect(0.5))
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis',linewidth=0,zorder=0)
ax.plot_surface(x_p, Y_p, Z_p, color='r',linewidth=0, alpha=0.5,zorder=5)
ax.plot(x_c,y_c,z_c,zorder=10)

plt.tight_layout()

显示不同 x_p 值的高斯形状重叠。假设对于 np.linspace(-10,10,20) 中的 x_p :

gaussian_overlap_gif

关于python - 在 3D 绘图 python 中的平面上绘制一维高斯分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com