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

Python - plot rectangles of known size at scatter points

我有一套积分:

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)

这使得这个情节:

--

我用一张图片覆盖它,其中每个散点都有一个球形斑点。我想拟合这个斑点,所以我在散点周围定义了一个矩形区域以执行拟合。

我想在图上看到这个矩形,以直观地查看它们是否大到足以包围 blob,如下所示:

我可以用 scatter 做吗?或者有什么其他方法可以做到吗?

您可以在 matplotlib.pyplot.scatterverts 选项中定义标记,就像 Understanding matplotlib verts and https://matplotlib.org/gallery/lines_bars_and_markers/scatter_custom_symbol.html

verts : sequence of (x, y), optional

If marker is None [ this is not entirely working, cf Understanding matplotlib verts ], these vertices will be used to construct the marker. The center of the marker is located at (0, 0) in normalized units. The overall marker is rescaled by 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))

来源:Understanding matplotlib verts

虽然@ralf-htp 的回答很好很干净并且使用 scatter,但据我所知,标记的比例是用 points 表示的(参见 here) .此外,如果放大,自定义标记不会改变大小。

也许这正是您要找的。如果不是,使用单独的 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 个实例