值列表列表的3D图

时间:2015-11-25 10:45:11

标签: python numpy matplotlib plot 3d

我试图从值列表列表中创建一个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 个答案:

答案 0 :(得分:1)

由于meshgrid输出的默认笛卡尔索引(有关详细信息,请参阅docs),data的形状为(6,12),但x和{{ 1}}具有(12,6)的形状。解决问题的最简单方法是转置y数组:

data

或者您可以将矩阵索引表示法应用于ax.plot_surface(x, y, data.T) 输出:

meshgrid