ely*_*ase 10 python matplotlib scatter-plot
我在matplotlib中使用方形标记进行散点图,如下所示:
.
我希望实现这样的目标:

这意味着我必须调整标记大小和图形大小/比例,使标记之间没有空白区域.每个索引单位也应该有一个标记(x和y都是整数),所以如果y从60变为100,则y方向应该有40个标记.目前我正在手动调整它.对于实现这一目标的最佳方法有什么想法吗?
我发现了两种方法:
第一个是基于这个答案.基本上,您可以确定相邻数据点之间的像素数,并使用它来设置标记大小.标记大小in scatter作为区域给出.
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
# initialize a plot to determine the distance between the data points in pixel:
x = [1, 2, 3, 4, 2, 3, 3]
y = [0, 0, 0, 0, 1, 1, 2]
s = 0.0
points = ax.scatter(x,y,s=s,marker='s')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])
# retrieve the pixel information:
xy_pixels = ax.transData.transform(np.vstack([x,y]).T)
xpix, ypix = xy_pixels.T
# In matplotlib, 0,0 is the lower left corner, whereas it's usually the upper
# right for most image software, so we'll flip the y-coords
width, height = fig.canvas.get_width_height()
ypix = height - ypix
# this assumes that your data-points are equally spaced
s1 = xpix[1]-xpix[0]
points = ax.scatter(x,y,s=s1**2.,marker='s',edgecolors='none')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])
fig.savefig('test.png', dpi=fig.dpi)
Run Code Online (Sandbox Code Playgroud)
第一种方法的缺点是符号重叠.我无法找到方法中的缺陷.我可以手动调整s1到
s1 = xpix[1]-xpix[0] - 13.
Run Code Online (Sandbox Code Playgroud)
为了给出更好的结果,但我无法确定背后的逻辑13..
因此,基于这个答案的第二种方法.在这里,在图上绘制单个正方形并相应地调整大小.在某种程度上,它是一个手动散点图(循环用于构造图形),因此根据数据集可能需要一段时间.
这种方法使用patches而不是scatter,所以一定要包括
from matplotlib.patches import Rectangle
Run Code Online (Sandbox Code Playgroud)
同样,使用相同的数据点:
x = [1, 2, 3, 4, 2, 3, 3]
y = [0, 0, 0, 0, 1, 1, 2]
z = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] # in your case, this is data
dx = [x[1]-x[0]]*len(x) # assuming equally spaced data-points
# you can use the colormap like this in your case:
# cmap = plt.cm.hot
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])
for x, y, c, h in zip(x, y, z, dx):
ax.add_artist(Rectangle(xy=(x-h/2., y-h/2.),
color=c, # or, in your case: color=cmap(c)
width=h, height=h)) # Gives a square of area h*h
fig.savefig('test.png')
Run Code Online (Sandbox Code Playgroud)
一条评论Rectangle:坐标是左下角,因此x-h/2.
这种方法给出了连接的矩形.如果我仔细观察这里的输出,他们似乎仍然重叠一个像素 - 再次,我不确定这可以帮助.