I was able to add a fill of a triangle onto my plot by following the format:
ax.fill([x1, x2, x3], [y1, y2, y3], 'r', alpha = 0.5)
But when I want to reuse the graph to show a different dataset, I cannot seem to be able to remove the fill object. My plot contains markers, lines and a single fill. What would be the best way to remove this fill?
Currently, when I want to reset my graph, I use:
EraseMarkers() # To remove markers
for i in ax.get_lines():
i.remove() # To remove lines
I tried use matplotlib's ax.cla()
function, but this doesn't satisfy my needs as it clears the entirety of my plot in which I would like to keep the image that I set as a background and other settings. Here is the code for setting up my plot:
fig = Figure(figsize = (9, 3.8), dpi = 100)
img = plt.imread('Rink2.png')
ax = fig.add_subplot(111)
img = ax.imshow(img, extent=[-100, 100, -42.5, 42.5])
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.axis('off')
I'd love to know an easier way to remove all plotted objects (Markers, lines & fill) without erasing my background and settings. Or just a way to remove the fill.
CodePudding user response:
It is possible to remove an element arbitrary element A
from a plot by using A.remove()
.
To do that, when you call ax.fill
you can store the return of this function to a variable, as
filled = ax.fill([x1, x2, x3], [y1, y2, y3], 'r', alpha = 0.5)
to remove it you can than use:
for f in filled:
f.remove()
see the minimum example below:
fig = plt.Figure(figsize=(10,10))
ax = fig.add_subplot(111)
x1, x2, x3 = 1, 2, 3
y1, y2, y3 = 0, 2, 0
fill = ax.fill([x1, x2, x3], [y1, y2, y3], 'r', alpha = 0.5)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
fig.savefig('test1.png')
for f in fill:
f.remove()
fig.savefig('test2.png')
PS: when adding the figure, is generally best to use the built-in constructors such as plt.subplots
or plt.figure
instead of accessing the class directly as in Figure