小编M. *_*nke的帖子

事件处理:Matplotlib的图()和pyplot的图()

正如在http://matplotlib.org/users/event_handling.html中所描述的那样,以下示例代码可以正常工作

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)
Run Code Online (Sandbox Code Playgroud)

但为什么呢

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)
Run Code Online (Sandbox Code Playgroud)

不工作(虽然它基本相同)?错误是

AttributeError: 'NoneType' object has no attribute 'mpl_connect'
Run Code Online (Sandbox Code Playgroud)

这真让我困惑,因为

type(fig)
Run Code Online (Sandbox Code Playgroud)

在两种情况下都按预期给出相同的结果:

<class 'matplotlib.figure.Figure'>
Run Code Online (Sandbox Code Playgroud)

python matplotlib

4
推荐指数
1
解决办法
1475
查看次数

标签 统计

matplotlib ×1

python ×1