2015-11-25 89 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')