从 x、y、z 值绘制的 matplotlib 2D 图

新手上路,请多包涵

我是 Python 初学者。

我有一个 X 值列表

x_list = [-1,2,10,3]

我有一个 Y 值列表

y_list = [3,-3,4,7]

然后我有每对夫妇的 Z 值。从原理上讲,它是这样工作的:

 X   Y    Z
-1  3    5
2   -3   1
10  4    2.5
3   7    4.5

Z 值存储在 z_list = [5,1,2.5,4.5] 中。我需要得到一个二维图,X 值在 X 轴上,Y 值在 Y 轴上,每对 Z 值由强度图表示。这是我尝试过的,但没有成功:

 X, Y = np.meshgrid(x_list, y_list)
fig, ax = plt.subplots()
extent = [x_list.min(), x_list.max(), y_list.min(), y_list.max()]
im=plt.imshow(z_list, extent=extent, aspect = 'auto')
plt.colorbar(im)
plt.show()

如何正确完成这项工作?

原文由 johnhenry 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
1 个回答

问题是 imshow(z_list, ...) 将期望 z_list 是一个 (n,m) 类型数组,基本上是一个值网格。要使用 imshow 函数,您需要为每个网格点设置 Z 值,这可以通过收集更多数据或插值来实现。

这是一个示例,使用您的数据进行线性插值:

 from scipy.interpolate import interp2d

# f will be a function with two arguments (x and y coordinates),
# but those can be array_like structures too, in which case the
# result will be a matrix representing the values in the grid
# specified by those arguments
f = interp2d(x_list,y_list,z_list,kind="linear")

x_coords = np.arange(min(x_list),max(x_list)+1)
y_coords = np.arange(min(y_list),max(y_list)+1)
Z = f(x_coords,y_coords)

fig = plt.imshow(Z,
           extent=[min(x_list),max(x_list),min(y_list),max(y_list)],
           origin="lower")

# Show the positions of the sample points, just to have some reference
fig.axes.set_autoscale_on(False)
plt.scatter(x_list,y_list,400,facecolors='none')

在此处输入图像描述

您可以看到它在您的样本点显示了正确的值(由 x_listy_list 指定,由半圆显示),但它在其他地方有更大的变化,由于插值的性质和少量的样本点。

原文由 Albert P 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题