Matplotlib说无花果帆布没有,所以我不能用无花果帆布.d

2024-10-05 19:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我没怎么用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负责一些幕后设置任务,最明显的是在图对象和所需的渲染器/后端之间建立连接。教程说:

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可以简化这项任务——只是试着探索所有的部分是如何组合在一起的。在

我看到了后端使用的基类的描述^{},我假设我需要分配fig.canvas其中一个FigureCanvasBase的子类。在

另外,我验证了Python使用的是默认后端。所以我知道这个问题不是由于缺少后端造成的。在

^{pr2}$

提前谢谢你的帮助。总之,有两个问题:

  1. 我错过了什么导致这个失败?是因为我没有给人物对象分配渲染器吗?在
  2. 我提到我怀疑我需要一个FigureCanvasBase的子类来向前推进。即使这个问题可以更优雅地解决,有没有办法在Python环境中搜索继承自FigureCanvasBase的子类?这可能在其他问题上有用。在

Tags: 代码绘图timematplotlibfigax子类we
1条回答
网友
1楼 · 发布于 2024-10-05 19:30:48

您需要创建一个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

注意:您可以在matplotlib.backends.<your backend>.FigureCanvas<your backend>中找到FigureCanvasBase的子类

相关问题 更多 >