简体   繁体   English

使用适用于Python的matplotlib,如何在用pcolor创建的单元格的中心绘制点?

[英]With matplotlib for Python, how to plot a dot in the center of cells that were created with pcolor?

I am using matplotlib.pyplot.pcolor to plot a 2D grid like the following: 我正在使用matplotlib.pyplot.pcolor绘制2D网格,如下所示:

PL.pcolor(array, cmap = PL.cm.YlOrRd, vmin = 0, vmax = 3)

Where array is just a simple 2D array. 其中array只是一个简单的2D数组。 That part works fine. 那部分工作正常。 But next I try: 但是接下来我尝试:

PL.hold(True)
PL.scatter(x, y, 'blue')
PL.hold(False)

Where x and y are the coordinates where I want a given dot to be plotted. 其中xy是我要绘制给定点的坐标。 However, instead of getting plotted in the center of the cells of the grid that is plotted with pcolor , the dot gets to the corner of the cells (no matter which cell I choose). 但是,不是将点绘制在使用pcolor绘制的网格的单元格的中心,而是将点移到单元格的角(无论我选择哪个单元格)。

You can use meshgrid to generate the mesh of points. 您可以使用meshgrid生成点的网格。 If your sampling x and y are uniform, then just add the separation divided by two in each direction. 如果您的采样x和y是均匀的,则只需在每个方向上将间隔除以2。 ie if separation is 1, then add 0.5 and subtract one point: 例如,如果间隔为1,则加0.5并减去1:

import numpy as np
import matplotlib.pyplot as plt
r = np.arange(10)
p = np.arange(10)
R,P = np.meshgrid(r,p)
data = np.random.random((10,10))
plt.pcolor(R,P,data)
plt.scatter(R[:-1,:-1]+0.5,P[:-1,:-1]+0.5, color = 'blue')

在此处输入图片说明

This is in case you use tripcolor : You can calculate the centroid of your points: triang.triangles gives you the three point indexes of each triangle, then you calculate the centroid using those three points. 这是在使用tripcolor情况下:可以计算点的质心: triang.triangles为您提供每个三角形的三个点索引,然后使用这三个点计算质心。 ie centroidX = (x1+x2+x3)/3.; centroidY = (y1+y2+y3)/3.; centroidX = (x1+x2+x3)/3.; centroidY = (y1+y2+y3)/3.; centroidX = (x1+x2+x3)/3.; centroidY = (y1+y2+y3)/3.;

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
triang = tri.Triangulation(x, y)
plt.tripcolor(triang,z)
centroidX = [x[i].sum()/3. for i in triang.triangles]
centroidY = [y[i].sum()/3. for i in triang.triangles]
plt.scatter(centroidX,centroidY, color = 'blue')

在此处输入图片说明

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM