Search code examples
pythonmatplotlibmatplotlib-widget

Python - matplotlib: how to change RectangleSelector properties


Is it possible to change RectangleSelector properties after it has been created?

Let's say I created a figure with the following rectangle:

from matplotlib.widgets import RectangleSelector
import matplotlib.pyplot as plt

def on_click(eclick, erelease):
    pass

fig, current_ax = plt.subplots()
RS = RectangleSelector(current_ax, on_click, drawtype='box', 
                        useblit=True, button=[1, 3], interactive=True,
                        minspanx=1, minspany=1, spancoords='pixels',
                        rectprops=dict(linestyle='-', color='g', 
                                       fill=True, alpha=1))
plt.show()

What if I want to change the rectangle color?

I would do:

RS.rectprops['color'] = 'r'
RS.canvas.draw()
fig.canvas.draw()

But this doesn't affect the color of the rectangle.

Any clue?

Thanks


Solution

  • If you want to update the rectangle patch you have drawn on the figure, not the widget, you can use:

    current_ax.patches[0].set_facecolor('r')
    

    or alternatively (credit to JohanC):

    RS.artists[0].set_facecolor('r')
    

    After clicking on the rectangle again, it will change color