Skip to main content
 首页 » 编程设计

Python/Pyplot : Plotting 2D-Data at given (X, Y)

2025年04月02日15bonelee

我有以下类型的一些数据: grid = np.array([posx, posy]) 其中 posx 和 posy 是一些 X/Y 位置,存储在另一个数组中。 (转置的)网格可能看起来像:

grid = np.array([posx, posy]) 
print grid.T   
[[   2.47685286    2.51629155] 
[   2.47685286    8.51629155] 
[   2.47685286   14.51629155] 
[   8.47685286    5.51629155] 
[   8.47685286   11.51629155] 
[  14.47685286    2.51629155] 
[  14.47685286    8.51629155] 
[  14.47685286   14.51629155]] 

尤其是每个“行”中的 y 位置不相同并且点数不同,我认为这是我的问题之一。

此外,相应的数据存储在另一个(1D-)数组中,如 data = [2.3 4.7 -0.3 .....] 具有与我的点数相同的条目数。 我的目标是将这些数据绘制成一种平滑的热图,通过颜色显示高/低值的位置。到目前为止我用过:

import numpy as np 
import matplotlib.pyplot as p 
p.imshow(data, interpolation=None) 
p.colorbar() 
p.show() 

显然我的问题是我需要调整点的位置。 我搜索了其他一些帖子,但使用这种数据形式从未解决过。 我也尝试通过简单地 reshape 数据来调整它,但由于点数不规则,这不起作用

因为我是新来的,所以我也很高兴收到有关如何改进我的帖子的评论(需要更多意见等) 提前致谢!

请您参考如下方法:

这个问题有多种解决方案。

如果您只是想将点显示为某种大小的标记,颜色取决于 z 数组中的值,那么散点图就可以了很好。但是,如果点之间的空间也应该着色,则应使用插值和等高线。幸运的是,这些东西也已经在 matplotlib 中实现了不规则间隔的数据(“unstructured grid”上的数据),这是你所拥有的,因为点不能轻易映射到规则网格(尽管在你给出的小例子中,似乎确实存在大小相等的三角形的趋势)。

以下 3 个示例说明了您可能想要进一步研究的函数:plt.scatter、plt.tripcolor 和 plt.tricontourf。我将数据集变大了一点,这样您就可以了解 z 表示的函数。

x,y = (2*np.random.rand(50)-1 for _ in range(2)) 
z = np.exp(-x*x - y*y) - np.cos(x)  # turtle-surface around origin 
f, ax = plt.subplots(1,3, sharex=True, sharey=True, num=2, subplot_kw={'xlim': (-1,1), 'ylim': (-1, 1)}) 
 
ax[0].scatter(x,y, s=500*(z-z.min()), c=z, cmap='hot') # scatterplot with variable-sized markers and colors 
ax[1].tripcolor(x, y, z, cmap='hot') # creates a tesselation and colors the formed triangles based on the values in the 3 nodes 
ax[2].tricontourf(x, y, z, cmap='hot') # estimates the underlying surface 
 
for indx in (1,2): 
    ax[indx].triplot(x,y, 'ko ') # add the locations of the points 
for axes in ax: # turn off the needless clutter 
    axes.tick_params(axis='both', which='both', bottom='off', left='off', labelbottom='off', labelleft='off') 
ax[0].set_title('scatter') 
ax[1].set_title('tripcolor') 
ax[2].set_title('tricontourf')