[英]Event handling: Matplotlib's Figure() and pyplot's figure()
正如在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'>
這是因為當您使用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.