Manually call draw for matplotlib

Question:

I have the following code example. When I press the button the color changes. However only after I move the mouse a little. Can I somehow directly call the draw function?

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

def toggle(_):
    button.status ^= True

    color = [0, 1, 0] if button.status else [1, 0, 0]
    button.color = color
    button.hovercolor = color

    # Stuff that doesn't work...
    plt.draw()
    button.canvas.draw()
    plt.gcf().canvas.draw()


button = Button(plt.axes([.1, .1, .8, .8]), 'Press me')
button.status = True
button.on_clicked(toggle)

plt.show() 
Asked By: magu_

||

Answers:

I am sure that there is an “official” way to do what you want to do, but here is a hack to simulate a mouse motion event which will trigger the redraw. Add button.canvas.motion_notify_event(0,0) at the end of toggle() so that your code looks like this:

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

def toggle(_):
    button.status ^= True

    color = [0, 1, 0] if button.status else [1, 0, 0]
    button.color = color
    button.hovercolor = color

    button.canvas.motion_notify_event(0,0)

button = Button(plt.axes([.1, .1, .8, .8]), 'Press me')
button.status = True
button.on_clicked(toggle)

plt.show() 
Answered By: Eric Dill

I had the same problem, and the answer by Eric Dill did not work for me. What worked instead was simply doing

canvas.draw_idle()

instead of

canvas.draw()

See here for more information about the difference between the two.

I’m not sure if this works for all backends, but in my case I’m using GTK3Agg.

Answered By: user3208430
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.