首页 > 解决方案 > python matplotlib.patches:绘制一个圆形补丁,但只保留圆形的一部分

问题描述

我正在尝试绘制图片,并且绘制了一个矩形,然后我想绘制一个弧形元素,但是这个元素必须是精确的,并且它只是矩形之外的圆的一部分。所以,我尝试使用 Arc patch 来创建相同的东西,但形状不匹配。

结果,我想知道是否可以绘制圆,但只保留它在矩形之外的部分?更具体地说,我想丢弃/隐藏/摆脱下图中的蓝色箭头部分,并保留红色箭头部分,它像弧形一样位于矩形之外。有什么方法可以做到吗? 在此处输入图像描述

这是我的代码:

from matplotlib.patches import Circle, Rectangle, Arc, Ellipse

def plot_pic(ax=None, color='black', lw=2, scale = 15):
    # get the current ax if ax is None
    if ax is None:
       ax = plt.gca()


    # Plot the rectangle
    rec =  Rectangle((-(7.32 * scale / 2+ 5.5 * scale +11 * scale),0), width = (5.5 * scale * 2 + 11 * scale * 2 + 7.32 * scale), height = 16.5 * scale, linewidth = lw, color = color, fill = False)

    testCircle = Circle((0, 11 * scale), radius = 9.15 * scale, color = color, lw = lw, fill = False)


    # List of elements to be plotted
    pic_elements = [rec, testCircle]


    # Add the elements onto the axes
    for element in pic_elements:
        ax.add_patch(element)

    return ax

在此之后,运行以下命令:

plt.figure(figsize=(16, 22))
plt.xlim(-600,600)
plt.ylim(-100,1700)
plot_pic()
plt.show()

非常感谢您的帮助。

标签: pythonmatplotlibseaborn

解决方案


如果真的只是按照您说的做,您可以将矩形的 facecolor 设置为whitezorder将圆的 设置为 ,0以便将其绘制在后面:

def plot_pic(ax=None, color='black', lw=2, scale = 15):
    # get the current ax if ax is None
    if ax is None:
       ax = plt.gca()


    # Plot the rectangle
    rec =  Rectangle((-(7.32 * scale / 2+ 5.5 * scale +11 * scale),0), width = (5.5 * scale * 2 + 11 * scale * 2 + 7.32 * scale), height = 16.5 * scale, linewidth = lw, color = color, fc='white')

    testCircle = Circle((0, 11 * scale), radius = 9.15 * scale, color = color, lw = lw, fill = False, zorder=0)


    # List of elements to be plotted
    pic_elements = [rec, testCircle]


    # Add the elements onto the axes
    for element in pic_elements:
        ax.add_patch(element)

    return ax

在此处输入图像描述


推荐阅读