Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting matplotlib plots to refresh on mouse focus

I am using matplotlib with interactive mode on and am performing a computation, say an optimization with many steps where I plot the intermediate results at each step for debugging purposes. These plots often fill the screen and overlap to a large extent.

My problem is that during the calculation, figures that are partially or fully occluded don't refresh when I click on them. They are just a blank grey.

I would like to force a redraw if necessary when I click on a figure, otherwise it is not useful to display it. Currently, I insert pdb.set_trace()'s in the code so I can stop and click on all the figures to see what is going on

Is there a way to force matplotlib to redraw a figure whenever it gains mouse focus or is resized, even while it is busy doing something else?

like image 571
Paul Avatar asked Nov 22 '11 10:11

Paul


Video Answer


1 Answers

Something like this might work for you:

import matplotlib.pyplot as plt
import numpy as np

plt.ion() # or leave this out and run with ipython --pylab

# draw sample data
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(np.random.rand(10))

class Refresher:
    # look for mouse clicks
    def __init__(self, fig):
        self.canvas = fig.canvas
        self.cid = fig.canvas.mpl_connect('button_press_event', self.onclick)

    # when there is a mouse click, redraw the graph
    def onclick(self, event):
        self.canvas.draw()

# remove sample data from graph and plot new data. Graph will still display original trace
line.remove()
ax.plot([1,10],[1,10])

# connect the figure of interest to the event handler 
refresher = Refresher(fig)
plt.show()

This will redraw the figure whenever you click on the graph.

You can also experiment with other event handling like

  • ResizeEvent - figure canvas is resized
  • LocationEvent - mouse enters a new figure

check more out here:

like image 53
Ben Avatar answered Oct 17 '22 06:10

Ben