[Python] Hollowing out a patch / "anticlipping" a patch in Matplotlib (Python)

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I want to draw a patch in Matplotlib constructed by hollowing it out with another patch, in a way such that the hollowed out part is completely transparent.

    For example, lets say I wanted to draw an ellipse hollowed out by another. I could do the following:

    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse

    ellipse_1 = Ellipse((0,0), 4, 3, color='blue')
    ellipse_2 = Ellipse((0.5,0.25), 2, 1, angle=30, color='white')

    ax = plt.axes()
    ax.add_artist(ellipse_1)
    ax.add_artist(ellipse_2)

    plt.axis('equal')
    plt.axis((-3,3,-3,3))
    plt.show()


    [​IMG]

    However, if now I wanted to draw something behind, the part behind the hollowed out part would not be visible, for example:

    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse, Rectangle

    ellipse_1 = Ellipse((0,0), 4, 3, color='blue')
    ellipse_2 = Ellipse((0.5,0.25), 2, 1, angle=30, color='white')
    rectangle = Rectangle((-2.5,-2), 5, 2, color='red')

    ax = plt.axes()
    ax.add_artist(rectangle)
    ax.add_artist(ellipse_1)
    ax.add_artist(ellipse_2)

    plt.axis('equal')
    plt.axis((-3,3,-3,3))
    plt.show()


    [​IMG]

    where the part of the red rectangle inside the blue shape cannot be seen. Is there an easy way to do this?

    Another way to solve this would be with a function to do the opposite of set_clip_path, lets say set_anticlip_path, where the line

    ellipse_1.set_anticlip_path(ellipse_2)


    would do the trick, but I have not been able to find anything like this.

    Continue reading...

Compartilhe esta Página