Python / Pyplot:在给定(X,Y)处绘制2D数据

时间:2016-05-18 09:01:23

标签: python matplotlib imshow

我有一些以下类型的数据: 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-Position在每个" row"并且点数不同,我认为这是我的一个问题。

此外,相应的数据存储在另一个(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()

显然我的问题是我需要调整积分的位置。 我搜索了其他一些帖子,但是这种形状的数据从未解决过。 此外,我试图通过简单地重塑数据来调整这一点,但由于点数不规则而无法正常工作

由于我是新来的,我也很高兴有关如何改进我的帖子的意见(需要更多输入等) 提前谢谢!

2 个答案:

答案 0 :(得分:1)

这个问题有几种解决方法。

如果你想要的只是将点显示为某种尺寸的标记,颜色取决于z数组中的值,那么散点图将很好地完成。但是,如果点之间的空间也应该是彩色的,则应使用插值和轮廓。幸运的是,这些东西也已在matplotlib中实现,用于不规则间隔的数据(" unstructured grid")上的数据,这就是你所拥有的,因为这些点不能轻易地映射到常规网格(尽管在您给出的小例子中,似乎存在等大小三角形的倾向。)

以下3个示例说明了您可能希望进一步查看的功能:plt.scatterplt.tripcolorplt.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')

illustration of plotting irregularly spaced (triangular) data

答案 1 :(得分:0)

我认为您的问题可以通过创建常规的2d矩阵然后使用scipy.interpolate在数据点之间插入数据来解决。示例可在以下位置找到:http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#id1