首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >事件处理:Matplotlib的Figure()和pyplot的figure()

事件处理:Matplotlib的Figure()和pyplot的figure()
EN

Stack Overflow用户
提问于 2015-08-11 12:44:18
回答 1查看 1.8K关注 0票数 4

正如在http://matplotlib.org/users/event_handling.html中描述的那样,下面的示例代码运行良好

代码语言:javascript
运行
复制
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)

但是为什么

代码语言:javascript
运行
复制
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)

不是工作(尽管它基本上是一样的)?错误是

代码语言:javascript
运行
复制
AttributeError: 'NoneType' object has no attribute 'mpl_connect'

这真的让我很困惑,因为

代码语言:javascript
运行
复制
type(fig)

在这两种情况下,都会产生相同的结果:

代码语言:javascript
运行
复制
<class 'matplotlib.figure.Figure'>
EN

回答 1

Stack Overflow用户

发布于 2015-08-11 13:25:31

这是因为当您使用Figure()创建独立的Figure实例时,画布不会自动设置,您必须使用方法- fig.set_canvas()设置画布。因为您没有这样做,所以fig.canvasNone,当您尝试使用- fig.canvas.mpl_connect时,您得到了AttributeError

但是当您使用pyplot并使用- plt.figure()获取图形时,它会为您创建画布。如果你想知道在哪里,那么matplotlib.pyplot.figure()内部使用matplotlib.backend.new_figure_manager()来创建图形,这(取决于后端)创建了图形,例如gtk可以使用here -第99行-

代码语言:javascript
运行
复制
canvas = FigureCanvasGTK(figure)
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31933393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档