2017-02-05 104 views
0

我想做的事情與this問題的答案一樣,但不是在MATLAB中,而是在Python中使用matplotlib。到目前爲止,我已經完成了三維繪圖的代碼投影多變量分佈到2D圖?

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

mu_x = 0 
mu_y = 0 

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], [[1, 0.8], [0.8, 1]]) 

fig = plt.figure(figsize=(10,5)) 
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') 
ax.auto_scale_xyz([-10, 10], [-10, 10], [0, 0.5]) 
plt.show() 

但是我怎樣才能把它投影到2D輪廓圖?我想

plt.figure() 
CS = plt.contour(X, Y, rv) 
plt.clabel(CS, inline=1, fontsize=10) 

但顯然這是不正確的,因爲Z是不是數組類型(我得到的線CS = plt.contour(X, Y, rv)錯誤TypeError: float() argument must be a string or a number)。我如何將多變量分佈投影到二維等高線圖上?謝謝!

回答

0

您需要提供與plot_surface相同的陣列給contour

CS = plt.contour(X, Y, rv.pdf(pos))