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

如何在Matplotlib中绘制尺度不变的直角标注

实现Matplotlib尺度不变直角角度标注的方案

核心思路

  • 继承Matplotlib官方角度标注的AngleAnnotation类,复用其内置的尺度不变坐标转换逻辑
  • 重写路径生成方法,将默认的弧形标注替换为直角折线样式,适配90度角的标注需求

完整实现代码

import matplotlib.pyplot as plt
from matplotlib.patches import AngleAnnotation
from matplotlib.transforms import Affine2D

class RightAngleAnnotation(AngleAnnotation):
    def __init__(self, *args, size=15, **kwargs):
        # 复用官方类的基础逻辑,固定角度为90度
        super().__init__(*args, angle=90, text="", **kwargs)
        # size为直角边的像素长度
        self.size = size

    def _get_path(self):
        # 计算直角两条边的单位向量
        v1 = self.vec1 / self.vec1_len * self.size
        v2 = self.vec2 / self.vec2_len * self.size
        # 构造直角折线的路径点
        path_points = [
            self.center + v1,
            self.center + v1 + v2,
            self.center + v2
        ]
        # 应用显示坐标仿射变换,保证缩放时标注不变形
        trans = Affine2D().rotate_deg(self.angle)
        return trans.transform_path(plt.Path(path_points))

使用示例

fig, ax = plt.subplots()
# 绘制两条垂直的参考线
ax.plot([0, 2], [0, 1], color="black")
ax.plot([0, 1], [0, -2], color="black")
# 加入直角标注
right_angle = RightAngleAnnotation(
    (0, 0),  # 直角顶点坐标
    (2, 1),  # 第一条边的任意端点
    (1, -2), # 第二条边的任意端点
    ax=ax,
    size=12,  # 直角边像素长度
    color="red",
    linewidth=2
)
ax.add_artist(right_angle)
# 可额外添加90°文本标注
ax.text(0.15, 0.15, "90°", transform=ax.transAxes, color="red")
ax.set_xlim(-0.5, 2.5)
ax.set_ylim(-2.5, 1.5)
plt.show()

特性说明

  • 标注尺寸以像素为单位,缩放、平移坐标轴时标注大小和直角形状不会发生变形,和官方弧形角度标注的尺度不变特性完全一致
  • 可通过size参数调整直角折线的边长,支持color、linewidth、linestyle等通用线条样式参数设置

内容的提问来源于stack exchange,提问作者Ben G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:36:01