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

如何在Matplotlib中绘制仅显示单条边的矩形?

解决方法:通过Rectangle参数直接指定仅显示上边

不用额外绘制直线,直接给Rectangle设置指定边的颜色就能实现需求,这样能完美对齐矩形角落,不会出现偏移问题。

Matplotlib的Rectangle支持通过edgecolor(或缩写ec)传入一个四元素列表,分别对应左、右、下、上四条边的颜色。把不需要显示的边设为None(或透明色),只保留上边的颜色即可。

修改后的完整代码

import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.patches import Rectangle

LIM = 5


def configure_plot(lim: float, **kwargs) -> tuple[Figure, Axes]:
    fig, ax = plt.subplots(**kwargs)
    ax.axis("equal")
    ax.set_axis_off()
    ax.set_xlim(-lim, lim)
    ax.set_ylim(-lim, lim)

    fig.tight_layout()
    return fig, ax


def main() -> None:
    fig, ax = configure_plot(LIM)

    width = 8
    height = 3.5
    color = "tab:blue"
    # 关键修改:edgecolor传入四元素列表,仅保留上边颜色
    rect = Rectangle(
        (-width / 2, -height),
        width,
        height,
        facecolor=color,
        alpha=0.8,
        linewidth=3,
        edgecolor=[None, None, None, color]  # 左、右、下无边框,上边框用指定颜色
    )
    ax.add_patch(rect)
    # 移除原来的plot直线代码

    plt.show()


if __name__ == "__main__":
    main()

说明

  • 这个方法直接复用了矩形的上边边框,完全和矩形对齐,不会出现线条超出角落的问题。
  • 如果不需要填充色,只需把facecolor设为None(或'none'),同时设置fill=False即可。

内容的提问来源于stack exchange,提问作者Shai Avr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:23:13