Python - 在散点处绘制已知大小的矩形

10

我有一组点:

a = ([126, 237, 116, 15, 136, 348, 227, 247, 106, 5, -96, 25, 146], [117, 127, 228, 107, 6, 137, 238, 16, 339, 218, 97, -4, -105])

然后我像这样制作了它们的散点图:

    fig = plt.figure(figsize = (15,6))
    ax = fig.add_subplot(111)
    ax.scatter(a[0], a[1], color = 'red', s=binradius)

这使得这个情节变得:

enter image description here

--

我正在将这个内容与一张图片叠加,图片中每个散点都有一个球形的斑点。我想要拟合这个斑点,因此我定义了一个矩形区域来执行拟合。我希望在图表上看到这个矩形,以便直观地判断它们是否足够大以包含斑点,如下所示:

enter image description here

我可以用scatter做吗?或者还有其他的方法吗?


https://dev59.com/3FoU5IYBdhLWcg3wc2xW - Joe
2个回答

9
尽管@ralf-htp的回答很好而且简洁,并使用了scatter,但据我所知,标记的比例是用points表示的(例如见这里)。此外,如果您放大,自定义标记的大小不会改变。
也许这正是您要寻找的。如果不是,使用单独的Rectangle对象也可以很好地解决问题。这允许您指定数据单位而不是点的宽度和高度,并且您可以缩放。如果必要,通过设置angle属性,也很容易应用旋转:
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle

# Your data
a = ([126, 237, 116, 15, 136, 348, 227, 247, 106, 5, -96, 25, 146],
     [117, 127, 228, 107, 6, 137, 238, 16, 339, 218, 97, -4, -105])

# Your scatter plot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(a[0], a[1], color = 'red', s=10)

# Add rectangles
width = 30
height = 20
for a_x, a_y in zip(*a):
    ax.add_patch(Rectangle(
        xy=(a_x-width/2, a_y-height/2) ,width=width, height=height,
        linewidth=1, color='blue', fill=False))
ax.axis('equal')
plt.show()

结果: 带有蓝色矩形的散点图 注意:如果需要,您可以通过ax.get_children()获取Rectangle实例。

你的答案真棒,超级有用。 - AturSams

1

您可以在matplotlib.pyplot.scatterverts选项中定义标记,就像理解matplotlib vertshttps://matplotlib.org/gallery/lines_bars_and_markers/scatter_custom_symbol.html中所示。

verts:(x,y)序列,可选

如果marker为None [这不完全有效,请参见 Understanding matplotlib verts],则将使用这些顶点构建标记。标记的中心位于规范化单位中的(0,0)处。整个标记通过s重新缩放。

来源: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html

但是,我不确定如何精确定义您绘制的标记,您必须构造一个包含所需标记像素的list

使用verts定义的矩形:

verts = list(zip([-10.,10.,10.,-10],[-5.,-5.,5.,5]))
ax.scatter([0.5,1.0],[1.0,2.0], marker=(verts,0))

来源: 理解matplotlib verts

1
在matplotlib 3.3.1中,我遇到了错误'<=' not supported between instances of 'list' and 'int'。设置marker=verts有所帮助。 - icemtel
但是当我更改数字时,标记器没有更改尺寸->因此如果有人阅读它,请注意。 - icemtel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接