You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过指定角点使用matplotlib.Patches绘制矩形?

关于Matplotlib Patches绘制矩形的问题解答

1. 是否可使用matplotlib.Patches仅通过指定角点绘制矩形?

当然可以!虽然patches.Rectangle本身的初始化逻辑是左下角顶点坐标 + 宽度 + 高度,但我们有两种灵活的实现思路:要么通过角点计算出Rectangle需要的参数,要么直接使用更通用的patches.Polygon(毕竟矩形是特殊的四边形,Polygon支持直接传入顶点坐标来绘制)。

2. 如何修改现有代码,通过指定角点坐标绘制矩形?

这里给你两种实用的实现方式,按需选择:

方法一:基于现有Rectangle类,通过角点推导参数

如果你想继续沿用熟悉的Rectangle,可以从四个角点中提取极值来计算宽高:

import matplotlib.pyplot as plt
from matplotlib import patches

fig, ax1 = plt.subplots()

# 假设你的四个角点坐标(需确保是矩形的顶点)
x1, y1 = 1, 2
x2, y2 = 3, 2
x3, y3 = 3, 5
x4, y4 = 1, 5

# 从角点中计算Rectangle所需的参数
x_coords = [x1, x2, x3, x4]
y_coords = [y1, y2, y3, y4]
bottom_left_x = min(x_coords)
bottom_left_y = min(y_coords)
rect_width = max(x_coords) - bottom_left_x
rect_height = max(y_coords) - bottom_left_y

# 沿用你原有的代码结构,替换成计算后的参数
patch = ax1.add_patch(patches.Rectangle((bottom_left_x, bottom_left_y), rect_width, rect_height))

# 调整坐标轴让矩形完整显示
ax1.set_xlim(bottom_left_x - 0.5, max(x_coords) + 0.5)
ax1.set_ylim(bottom_left_y - 0.5, max(y_coords) + 0.5)
plt.show()

方法二:用Polygon直接传入角点坐标(更直观)

如果不想折腾参数计算,直接用Polygon更省心——只要把四个角点按顺时针/逆时针顺序传入,它会自动闭合图形:

import matplotlib.pyplot as plt
from matplotlib import patches

fig, ax1 = plt.subplots()

# 按顺序排列的四个角点坐标(比如顺时针遍历矩形顶点)
corners = [(1,2), (3,2), (3,5), (1,5)]

# 创建多边形补丁,closed=True确保图形自动闭合
patch = ax1.add_patch(patches.Polygon(corners, closed=True, facecolor='none', edgecolor='black'))

# 自动适配坐标轴范围
ax1.autoscale()
plt.show()

注意:传入角点时必须按顺序排列(比如从左下角开始顺时针走一圈),否则画出的图形可能会扭曲变形。

内容的提问来源于stack exchange,提问作者Anam Nizami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:50:31