正如在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)
这是因为当您使用创建独立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它的示例在这里可用- 第99行 -
canvas = FigureCanvasGTK(figure)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1475 次 |
| 最近记录: |