Reputation: 41
As desribed in http://matplotlib.org/users/event_handling.html the following example code works fine
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))
def onclick(event):
print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
event.button, event.x, event.y, event.xdata, event.ydata)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
But why does
from matplotlib.figure import Figure
fig = Figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))
def onclick(event):
print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
event.button, event.x, event.y, event.xdata, event.ydata)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
not work (although it is basically the same)? The error is
AttributeError: 'NoneType' object has no attribute 'mpl_connect'
This really confuses me, as
type(fig)
gives as expected the same result in both cases:
<class 'matplotlib.figure.Figure'>
Upvotes: 4
Views: 2236
Reputation: 91009
That is because when you create a standalone Figure
instance using Figure()
, the canvas is not automatically set , you have to set the canvas using the method - fig.set_canvas()
. Since you did not do this fig.canvas
is None
and when you tried to - fig.canvas.mpl_connect
you got the AttributeError
.
But when you use pyplot
and get the figure using - plt.figure()
- it creates the canvas for you. If you are wondering where , then matplotlib.pyplot.figure()
internally uses matplotlib.backend.new_figure_manager()
to create the figure, and that (depending on the backend) creates the figure , Example for gtk
it is available here - line 99 -
canvas = FigureCanvasGTK(figure)
Upvotes: 6