matplotlib从x、y、z值绘制二维图

2024-04-25 13:27:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个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()

如何正确完成这项工作?


Tags: 列表npfigpltminextentmaxlist
2条回答

问题是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')

enter image description here

您可以看到它在您的采样点处显示正确的值(由x_listy_list指定,由半圆表示),但由于插值的性质和采样点的数量较少,它在其他位置的变化要大得多。

有一种方法:

import matplotlib.pyplot as plt
import nupmy as np
from matplotlib.colors import LogNorm

x_list = np.array([-1,2,10,3])
y_list = np.array([3,-3,4,7])
z_list = np.array([5,1,2.5,4.5])

N = int(len(z_list)**.5)
z = z_list.reshape(N, N)
plt.imshow(z, extent=(np.amin(x_list), np.amax(x_list), np.amin(y_list), np.amax(y_list)), norm=LogNorm(), aspect = 'auto')
plt.colorbar()
plt.show()

enter image description here

我跟踪了这个链接:How to plot a density map in python?

相关问题 更多 >