在python中可视化同一图形上的三维条形图和曲面图

2024-05-28 19:14:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较二元随机变量的直方图和它的概率分布。我已经为它写了代码,我得到了一个数字上的两个情节。但我无法区分两者。条形图掩盖了曲面图。你知道吗

如何更改颜色或任何其他参数,以便将它们显示在一起并比较两个绘图?你知道吗

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from mpl_toolkits.mplot3d import Axes3D

mu_x = 0
variance_x = 1
mu_y = 0
variance_y = 1
sample=1000

x, y = np.random.multivariate_normal((mu_x, mu_y), [[variance_x, 0], [0, variance_y]], sample).T
hist, xedges, yedges = np.histogram2d(x, y, bins=100, range=[[-10, 10], [-10, 10]],density=True)
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()

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

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
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()

Tags: posimportnppltaxmultivariatenormalset
1条回答
网友
1楼 · 发布于 2024-05-28 19:14:08

您可以简单地添加一个偏移量(您可以指定您喜欢的任何数量)到直方图,使两者都落在彼此的顶部,然后将一些透明度的直方图,以看到基本的轮廓。您可以在图的标题中提到,为了表示的目的添加了偏移量。所以具体来说,你可以用

ax.bar3d(xpos, ypos, zpos+0.35, dx, dy, dz, color='b', zsort='average')
ax.plot_surface(X, Y, rv.pdf(pos),cmap='viridis',linewidth=0)

产生

enter image description here

相关问题 更多 >

    热门问题