x,y,z值的matplotlib 2D图 [英] matplotlib 2D plot from x,y,z values

查看:46
本文介绍了x,y,z值的matplotlib 2D图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python初学者.

I am a Python beginner.

我有一个X值列表

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

我有一个 Y 值列表

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

然后我为每对夫妇设置一个 Z 值.从原理上讲,这是这样工作的:

I then have a Z value for each couple. Schematically, this works like that:

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 值,由强度图表示.这是我尝试过的尝试,但未成功:

and the Z values are stored in z_list = [5,1,2.5,4.5]. I need to get a 2D plot with the X values on the X axis, the Y values on the Y axis, and for each couple the Z value, represented by an intensity map. This is what I have tried, unsuccessfully:

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()

如何正确完成这项工作?

How to get this done correctly?

推荐答案

问题在于 imshow(z_list, ...) 会期望 z_list 成为 (n,m) 类型数组,基本上是值的网格.要使用imshow功能,每个网格点都需要具有Z值,这可以通过收集更多数据或进行插值来实现.

The problem is that imshow(z_list, ...) will expect z_list to be an (n,m) type array, basically a grid of values. To use the imshow function, you need to have Z values for each grid point, which you can accomplish by collecting more data or interpolating.

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

Here is an example, using your data with linear interpolation:

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_list y_list 指定),但在其他地方,由于插值的性质和样本点数较少.

You can see that it displays the correct values at your sample points (specified by x_list and y_list, shown by the semicircles), but it has much bigger variation at other places, due to the nature of the interpolation and the small number of sample points.

这篇关于x,y,z值的matplotlib 2D图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆