python matplotlib.patches:绘制一个Circle补丁,但仅保留一部分圆圈

时间:2018-07-28 17:17:38

标签: python matplotlib seaborn

我正在尝试绘制图片,并且绘制了一个矩形,然后我想绘制一个弧形元素,但是此元素必须精确,并且它只是矩形外部的一个圆的一部分形状。因此,我尝试使用Arc补丁创建相同的内容,但是形状不匹配。

因此,我想知道是否可以绘制圆形,但仅保留矩形之外的部分?更具体地说,我想在下图中丢弃/隐藏/消除“蓝色箭头”部分,并保留“红色箭头”部分,该部分位于矩形外(如弧形)。有什么办法吗? enter image description here

这是我的代码:

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()

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

如果仅是按照您说的去做,则可以将矩形的面色设置为white,将圆的zorder设置为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

enter image description here