正如在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'>发布于 2015-08-11 13:25:31
这是因为当您使用Figure()创建独立的Figure实例时,画布不会自动设置,您必须使用方法- fig.set_canvas()设置画布。因为您没有这样做,所以fig.canvas是None,当您尝试使用- fig.canvas.mpl_connect时,您得到了AttributeError。
但是当您使用pyplot并使用- plt.figure()获取图形时,它会为您创建画布。如果你想知道在哪里,那么matplotlib.pyplot.figure()内部使用matplotlib.backend.new_figure_manager()来创建图形,这(取决于后端)创建了图形,例如gtk可以使用here -第99行-
canvas = FigureCanvasGTK(figure)https://stackoverflow.com/questions/31933393
复制相似问题