我有这种形式的 csv 数据:
X,Y,Z
0,0,0.0
0,1,0.0
1,0,1.0
1,1,0.55
2,0,4.0
2,1,3.216
我不确定如何将此数据提供给 pcolormesh
。我想我必须使用 np.meshgrid
但我不确定在这种情况下该怎么做。
dat = pd.read_csv('my_dat.csv')
plt.pcolormesh(dat['X'], dat['Y'], dat['Z'])
plt.show()
导致 Value error: need more than one value to unpack
我不明白 - 为什么这不起作用?
最佳答案
您的数据只需要 reshape 。无需在此处使用 np.meshgrid
,因为您已经为每个单元格设置了 x 和 y 坐标。
如果您在 x 中有 nx
坐标,在 y 中有 ny
坐标,那么您可以这样做:
X = dat['X'].reshape(nx,ny).T
Y = dat['Y'].reshape(nx,ny).T
Z = dat['Z'].reshape(nx,ny).T
plt.pcolormesh(X,Y,Z)
plt.show()
请注意,pcolormesh 更喜欢您的 x
和 y
维度比 z
维度大一维,因为 x
和 y
定义单元格的边缘,z
定义单元格中心的颜色。来自文档:
Ideally the dimensions of X and Y should be one greater than those of C; if the dimensions are the same, then the last row and column of C will be ignored.
因此,在您的示例中,最后一行和最后一列的颜色将丢失,除非您添加一行和一列虚拟单元格,其 x 和 y 坐标比您的单元格数大 1。另一种可能是使用 plt.contourf
,其中 x、y 和 z 的长度应该相同。
关于python - matplotlib 将来自 csv 的 X Y Z 数据绘制为 pcolormesh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35168638/