Reputation: 232
Is there any way to update the title of a Matplotlib figure after the user has zoomed in? For example, I would like the title to display the exact extends of the x-axis,
import pylab as pl
import numpy as np
x = np.arange(10,step=0.1)
y = np.sin(x)
f = pl.figure()
pl.plot(x,y)
def my_ondraw(ev):
x1,x2 = f.gca().get_xlim() # FIXME value hasn't been updated yet
pl.title("x = [%f, %f]" % (x1,x2))
f.canvas.mpl_connect('draw_event', my_ondraw)
pl.show()
As noted, my code doesn't get the right values back from get_xlim() because the re-draw hasn't been done at the time my_ondraw is called...
Any suggestions?
Modified code that works based on Ilya's suggestion below:
import pylab as pl
import numpy as np
x = np.arange(10,step=0.1)
y = np.sin(x)
f = pl.figure()
ax = f.gca()
pl.plot(x,y)
def my_ondraw(ev):
print "my_ondraw: %s" % ev.name
x1,x2 = f.gca().get_xlim() # FIXME value hasn't been updated yet
pl.title("x = [%f, %f]" % (x1,x2))
ax.callbacks.connect('xlim_changed', my_ondraw)
pl.show()
Upvotes: 0
Views: 603
Reputation: 4689
You can register callback functions on the xlim_changed
and ylim_changed
events. Try something like this:
def on_xylims_change(axes):
x1,x2 = f.gca().get_xlim() # FIXME value hasn't been updated yet
pl.title("x = [%f, %f]" % (x1,x2))
fig, ax = pl.subplots(1, 1)
ax.callbacks.connect('xlim_changed', on_xylims_change)
ax.callbacks.connect('ylim_changed', on_xylims_change)
You can read more about it here: Event handling and picking in Matplotlib.
Upvotes: 1