值列表的 3D 图

3D plot of a list of lists of values

我正在尝试根据值列表制作 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()

谢谢

由于 meshgrid 输出的默认笛卡尔索引(有关更多信息,请参阅 docs),您的 data 的形状为 (6, 12),但 xy 的形状为 (12, 6)。最简单的解决方法就是转置data数组:

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

或者您可以将矩阵索引符号应用于 meshgrid 输出:

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