【问题标题】:Event handling: Matplotlib's Figure() and pyplot's figure()事件处理:Matplotlib 的 Figure() 和 pyplot 的 figure()
【发布时间】:2015-08-11 13:25:31
【问题描述】:

正如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)

为什么会这样

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)

不行(虽然基本一样)?错误是

AttributeError: 'NoneType' object has no attribute 'mpl_connect'

这真的让我很困惑,因为

type(fig)

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

<class 'matplotlib.figure.Figure'>

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    那是因为当你使用 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 行 -

    canvas = FigureCanvasGTK(figure)
    

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 2022-11-14
      • 2012-03-25
      • 1970-01-01
      • 2021-06-01
      • 2014-08-08
      • 2014-04-10
      • 2012-07-15
      • 2014-11-15
      相关资源
      最近更新 更多