首页 > 解决方案 > 使用 Python 绘制双变量分布的 3D 图

问题描述

我有一个具有以下参数的双变量分布:

Ux = 0.487889
Uy = 0.483756
Var(X) = 0.094482
Var(Y) = 0.073845
Covar(X,Y) = 0.078914

如何使用 python 制作这个的 3d 曲面图?

标签: pythonpython-3.xmatplotlibplot

解决方案


正如评论所暗示的那样,实际上有无数种方法可以回答这个问题。展示您迄今为止尝试过的代码并提供上下文非常重要,以便贡献者可以最好地帮助您。我使用了 PyCharm 2018.2.4 和 Python 3.6。以下代码假设了很多,并且不包括您提供的协方差,但它可能会让您朝着正确的方向前进:

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

#Parameters to set
mu_x = 0.487889
variance_x = 0.094482

mu_y = 0.483756
variance_y = 0.073845

#Create grid and multivariate normal
x = np.linspace(-0.5,1.5,500)
y = np.linspace(-0.5,1.5,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]])

#Make a 3D plot
fig = plt.figure()
ax = fig.gca(projection='3d')
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()

这提供了以下图表:

使用 PyCharm 从 Python 进行二元分布


推荐阅读