简体   繁体   English

来自 x、y、z 值的 matplotlib 2D 图

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

I am a Python beginner.我是 Python 初学者。

I have a list of X values我有一个 X 值列表

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

and I have a list of Y values我有一个 Y 值列表

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

I then have a Z value for each couple.然后我有每对夫妇的 Z 值。 Schematically, this works like that:从原理上讲,它是这样工作的:

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

and the Z values are stored in z_list = [5,1,2.5,4.5] . Z 值存储在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.我需要得到一个 2D 图,其中 X 轴上的 X 值、Y 轴上的 Y 值以及由强度图表示的每一对 Z 值。 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?如何正确完成这项工作?

The problem is that imshow(z_list, ...) will expect z_list to be an (n,m) type array, basically a grid of values.问题是imshow(z_list, ...)会期望z_list是一个(n,m)类型的数组,基本上是一个值网格。 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.要使用 imshow 函数,您需要为每个网格点设置 Z 值,这可以通过收集更多数据或插值来完成。

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

在此处输入图片说明

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_listy_list指定,由半圆显示)显示正确的值,但由于插值的性质和样本点的数量很少,它在其他地方的变化更大.

Here is one way of doing it:这是一种方法:

import matplotlib.pyplot as plt
import numpy 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()

在此处输入图片说明

I followed this link: How to plot a density map in python?我点击了这个链接: 如何在 python 中绘制密度图?

I am not as sharp when it comes to use python and matplotlib, but I wanted to share my experience.在使用 python 和 matplotlib 时我没有那么敏锐,但我想分享我的经验。 My trouble is that my X and Y datasets were not the same length, as well as being relatively heavy datasets, which turned out to be dysfunctional using any of the methods mentioned above.我的问题是我的 X 和 Y 数据集长度不一样,而且是相对较重的数据集,使用上述任何方法都证明是功能失调的。 Therefore, I used the heavy, inelegant method with a loop to populate the Z matrix.因此,我使用带有循环的繁重、不雅的方法来填充 Z 矩阵。 It takes 2-3 minutes on my laptop, but it does exactly what I want.在我的笔记本电脑上需要 2-3 分钟,但它完全符合我的要求。

"""
@author: Benoit
"""
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
import matplotlib.cm as cm


data = np.genfromtxt('MY_DATA_FILE.csv', delimiter=';', skip_header = 1)


#list of X, Y and Z
x_list = data[:,0]
y_list = data[:,1]
z_list = data[:,2]

length = np.size(x_list)

#list of X and Y values (np.unique removes redundancies)
N_x = np.unique(x_list)
N_y = np.unique(y_list)
X, Y = np.meshgrid(N_x,N_y)

length_x = np.size(N_x)
length_y = np.size(N_y)

#define empty intensity matrix
Z = np.full((length_x, length_y), 0)


#the f function will chase the Z values corresponding
# to a given x and y value

def f(x, y):
    for i in range(0, length):
        if (x_list[i] == x) and (y_list[i] == y):
            return z_list[i]
        
#a loop will now populate the Z matrix
for i in range(0, length_x - 1):
    for j in range(0, length_y - 1):
        Z[i,j] = f(N_x[i], N_y[j])

#and then comes the plot, with the colour-blind-friendly viridis colourmap
plt.contourf(X, Y, np.transpose(Z), 20, origin = 'lower', cmap=cm.viridis, alpha = 1.0);
cbar = plt.colorbar()
cbar.set_label('intensity (a.u.)')

#optional countour lines:
"""contours = plt.contour(X, Y, np.transpose(Z), colors='black');
plt.clabel(contours, inline=True, fontsize=8)
"""
plt.xlabel('X_TITLE (unit)')
plt.ylabel('Y_TITLE (unit)')
plt.axis(aspect='image')

plt.show()
plt.savefig('TYPE_YOUR_NAME.png', DPI = 600)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 meshgrid 将 X,Y,Z 三元组转换为三个 2D arrays for surface plot in matplotlib - Using meshgrid to convert X,Y,Z triplet to three 2D arrays for surface plot in matplotlib 使用色彩图在二维平面上绘制(x,y,z)三倍 - Plot (x, y, z) triples on 2d plane with a colormap 二维密度 Plot 与 XYZ 数据 - 2D Density Plot with X Y Z data 当从 2d 过渡到 3d 时,z 值似乎映射到不正确的 x 和 y 值 - z values appear to be mapping to the incorrect x and y values when transition from 2d to 3d 在二维 Numpy 数组中查找值 x、y、z 的行 - Finding a row in 2d Numpy array with values x,y,z in python-将x,y,z值映射到2D表面数据 - python - map x, y, z values to 2D surface data Python-在2D网格上对x,y,z值进行装箱 - Python - Binning x,y,z values on a 2D grid 如何获得轮廓 plot 和 3D plot 使用 z1587383CF8C21507D06FB 的 zDDDA 和 a set5ZEF3 列的起始点来表示? - How can I obtain a contour plot and a 3D plot using Matplotlib starting from a set of 3 columns representing x,y and z points? 如何制作 3D plot(X,Y,Z),将 Z 值分配给 X,Y 有序对? - How to make a 3D plot (X, Y, Z), assigning Z values to X,Y ordered pairs? Plot 3d 点 (x,y,z) in 2d plot with colorbar - Plot 3d points (x,y,z) in 2d plot with colorbar
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM