我没怎么用过 Matplotlib。根据某人的建议,我尝试尽可能多地使用面向对象的范例编写一些绘图代码---因此尝试使用纯 Matplotlib(即不依赖 pyplot)来生成一些简单的图形。
我的代码的精简版本如下所示:
import matplotlib as mpl
time = [0,1,2,3,4]
cell = [1,2,1,2,1]
sample = [3,2,3,4,4]
(figHt, figWd) = (5, 8) # in
lBorderWidth = bBorderWidth = rBorderWidth = tBorderWidth = 0.1
lbwh = (lBorderWidth, bBorderWidth,
(1-lBorderWidth-rBorderWidth),
(1-tBorderWidth-bBorderWidth)) # left, bottom, width, height
fig = mpl.figure.Figure(figsize=(figHt, figWd))
ax = fig.add_axes(lbwh)
lines1, = ax.plot(time,cell,'k--')
lines2, = ax.plot(time,sample,'k-')
fig.legend([lines1,lines2],['p','q'],'upper left')
fig.canvas.draw()
但是当我运行它时,Python 在到达 fig.canvas.draw() 时提示说 canvas 类型是 None。
基于对 Matplotlib Artists tutorial 的阅读,似乎 pyplot 负责一些幕后设置任务,最显着的是建立 Figure 对象和所需渲染器/后端之间的连接。教程说:
In the example below, we create a Figure instance using matplotlib.pyplot.figure(), which is a convenience method for instantiating Figure instances and connecting them with your user interface or drawing toolkit FigureCanvas. As we will discuss below, this is not necessary – you can work directly with PostScript, PDF Gtk+, or wxPython FigureCanvas instances, instantiate your Figures directly and connect them yourselves – but since we are focusing here on the Artist API we’ll let pyplot handle some of those details for us
不幸的是,该特定页面除了使用 pyplot.figure() 生成图之外没有继续进行,所以我仍在尝试发现所需的步骤是什么。再一次,我意识到 pyplot 可以简化这个任务——只是想弄清楚所有部分是如何组合在一起的。
我看到了后端使用的基类的描述,FigureCanvasBase ,我假设我需要分配 fig.canvas FigureCanvasBase 的子类之一。
此外,我还验证了 Python 使用的是默认后端。所以我知道问题不是由于缺少后端造成的。
>>> matplotlib.backends.backend
'Qt4Agg'
在此先感谢您的帮助。总结起来,两个问题:
- 我错过了什么导致失败?是因为我没有为图形对象分配渲染器吗?
- 我提到我怀疑我需要
FigureCanvasBase的子类才能继续。即使这个问题可能可以更优雅地解决,有没有办法在 Python 环境中搜索继承自 FigureCanvasBase 的子类?这在其他问题中可能会派上用场。
请您参考如下方法:
您需要创建一个 FigureCanvasAgg为了手动绘制,试试这个:
import matplotlib as mpl
mpl.use('Agg') #setup the backend
import matplotlib.figure as mfigure
from matplotlib.backends.backend_agg import FigureCanvasAgg #canvas
time = [0,1,2,3,4]
cell = [1,2,1,2,1]
sample = [3,2,3,4,4]
(figHt, figWd) = (5, 8) # in
lBorderWidth = bBorderWidth = rBorderWidth = tBorderWidth = 0.1
lbwh = (lBorderWidth, bBorderWidth,
(1-lBorderWidth-rBorderWidth),
(1-tBorderWidth-bBorderWidth)) # left, bottom, width, height
fig = mfigure.Figure(figsize=(figHt, figWd))
canvas = FigureCanvasAgg(fig) #create the canvas
ax = fig.add_axes(lbwh)
lines1, = ax.plot(time,cell,'k--')
lines2, = ax.plot(time,sample,'k-')
fig.legend([lines1,lines2],['p','q'],'upper left')
fig.savefig('test.png') #save the figure
注意:你可以找到FigureCanvasBase的子类在 matplotlib.backends.<your backend>.FigureCanvas<your backend>
