Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib remove patches from figure

Tags:

In my case, I want to remove one of the circle when clicking reset button. However, ax.clear() would clear all circles on the current figure.

Can someone tell me how to remove only part of the patches?

import matplotlib.patches as patches import matplotlib.pyplot as plt from matplotlib.widgets import Button  fig = plt.figure() ax = fig.add_subplot(111)   circle1 = patches.Circle((0.3, 0.3), 0.03, fc='r', alpha=0.5) circle2 = patches.Circle((0.4, 0.3), 0.03, fc='r', alpha=0.5) button = Button(plt.axes([0.8, 0.025, 0.1, 0.04]), 'Reset', color='g', hovercolor='0.975') ax.add_patch(circle1) ax.add_patch(circle2)  def reset(event):     '''what to do here'''     ax.clear()  button.on_clicked(reset) plt.show() 
like image 481
Idealist Avatar asked Feb 10 '14 20:02

Idealist


People also ask

How do I get rid of tick marks in matplotlib?

To remove the ticks on both the x-axis and y-axis simultaneously, we can pass both left and right attributes simultaneously setting its value to False and pass it as a parameter inside the tick_params() function. It removes the ticks on both x-axis and the y-axis simultaneously.

What does PLT CLF () do?

clf() - Clear the current figure.

What does .patches do in python?

patches. Rectangle class is used to rectangle patch to a plot with lower left at xy = (x, y) with specified width, height and rotation angle.


2 Answers

Try this:

def reset(event):     circle1.remove() 

Also maybe you prefer:

def reset(event):     circle1.set_visible(False) 
like image 78
Alvaro Fuentes Avatar answered Sep 18 '22 10:09

Alvaro Fuentes


Different options is this

def reset(event):     ax.patches = [] 

it removes all the patches. This option was viable for Matplotlib < 3.5.0. With Matplotlib 3.5.0 you get the error AttributeError: can't set attribute

In that case, you can use the following option

def reset(event):     ax.patches.pop()     # Statement below is optional     fig.canvas.draw() 
like image 31
zwep Avatar answered Sep 21 '22 10:09

zwep