2015-11-25 86 views
0

我想從值列表中做出一個3d圖。所有的子列表都有相同數量的值。值列表的列表的三維圖

我嘗試這樣做:Plot a 3d surface from a 'list of lists' using matplotlib,但我得到的錯誤:

ValueError: shape mismatch: objects cannot be broadcast to a single shap 

下面是如何重現:

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

list_of_lists = [[1,2,3,4,1,2,3,4,1,2,3,4],[2,3,5,9,2,3,5,9,2,3,5,9],[5,9,8,1,5,9,8,1,5,9,8,1],[1,2,3,4,1,2,3,4,1,2,3,4],[2,3,5,9,2,3,5,9,2,3,5,9],[5,9,8,1,5,9,8,1,5,9,8,1]] 

data = np.array(list_of_lists) 
length = data.shape[0] 
width = data.shape[1] 
x, y = np.meshgrid(np.arange(length), np.arange(width)) 

fig = plt.figure() 
ax = fig.add_subplot(1,1,1, projection='3d') 
ax.plot_surface(x, y, data) 
plt.show() 

謝謝

回答

1

由於默認meshgrid輸出的笛卡爾索引(有關更多信息,請參閱docs)您的data的形狀爲(6,12),但是x和(12,6)的形狀爲y。解決這一問題的最簡單方法是轉data陣列:

ax.plot_surface(x, y, data.T) 

或者你也可以申請矩陣索引符號來meshgrid輸出:

x, y = np.meshgrid(np.arange(length), np.arange(width), indexing='ij')