简体   繁体   中英

Clipping in Matplotlib. Why doesn't this work?

I'm attempting to clip shapes like circles and ellipses using clipping in Matplotlib, but there must be something I am missing.. Why doesn't this clip the circle in half?:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.transforms import Bbox

clip_box = Bbox(((-2,-2),(2,0)))
circle = Circle((0,0),1,clip_box=clip_box,clip_on=True)

plt.axes().add_artist(circle)
plt.axis('equal')
plt.axis((-2,2,-2,2))
plt.show()

I do not know why your code does not work, however, the following snippet works as you expect.

From my undestanding, clip_on is not related to applying a given clipping to a shape but wether the shape should clip in the display area.

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

rect = Rectangle((-2,-2),4,2, facecolor="none", edgecolor="none")
circle = Circle((0,0),1)

plt.axes().add_artist(rect)
plt.axes().add_artist(circle)

circle.set_clip_path(rect)

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

I've been struggling with this, so here's my version :

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.transforms import Bbox



# This is in PIXELS
# first tuple : coords of box' bottom-left corner, from the figure's bottom-left corner
# second tuple : coords of box' top-right corner, from the figure's bottom-left corner
clip_box = Bbox(((0,0),(300,300)))
circle = Circle((0,0),1)

plt.axis('equal')
plt.axis((-2,2,-2,2))
plt.axes().add_artist(circle)

# You have to call this after add_artist()
circle.set_clip_box(clip_box)

plt.show()

The two differences are that the box' coords are in pixels (?!), and that set_clip_box() only works after add_artists() (which is why clip_box=clip_box doesn't work). I'd love to know what should be configured to get this working in "axes units" instead.

For posterity, here's the hack I've used to troubleshoot this. It clips everything , including the plots, axes, etc :

for o in plt.findobj():
    o.set_clip_on(True)
    o.set_clip_box(clip_box)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM