Matplotlib子图-savefig()将不会输出PDF.“无类型"错误 [英] Matplotlib subplots figure - savefig() won't output PDF. "NoneType" error
问题描述
以下是我正在编写的代码的简化版本,以制作带有多个子图的图形.问题出现在最后一行 fig.savefig("foo" + ".pdf", format='pdf')
.我收到以下错误:
The following is a stripped-down version of a code I am writing to make a figure with several subplots. The problem arises in the last line, fig.savefig("foo" + ".pdf", format='pdf')
. I get the following error:
AttributeError: "'NoneType' object has no attribute 'print_figure'"
谁能告诉我怎么了?谢谢!
Can anyone tell me what's wrong? Thanks!
import matplotlib.pyplot as plt
from pdb import set_trace as st
import numpy as np
Time = np.array([0,1,2,3,4])
Load = np.array([1,2,3,4,5])
Cell = np.array([6,9,2,5,4])
axialLoadDueToCellPressure = 5.5 * Cell
volumePlotFormat = 'double-wide'
fig = plt.Figure()
ax1 = plt.subplot2grid((3,2), (0,0))
ax1.plot((Time/1000/60),
(Load + axialLoadDueToCellPressure)/6, 'k-')
ax1.plot((Time/1000/60), Cell, 'k--')
st()
fig.savefig("foo" + ".pdf", format='pdf')
推荐答案
问题出在画布上,在使用 fig.savefig() 方法时.此时 pyplot 已附加到 Canvas,但您的图形没有.我同意你的看法,这很出乎意料.如果您明确地将图形附加到画布,这不会成为问题.例如添加行:
The problem is with the canvas, when using the fig.savefig() method. At this point pyplot is attached to a Canvas, but your figure does not. I agree with you that this is rather unexpected. This wouldn't be a problem if you were explicitly attaching the Figure to a Canvas. For instance adding the line:
fig.set_canvas(plt.gcf().canvas)
将解决此问题.因此,您的整个代码应为:
Will fix this issue. So your entire code would be:
import matplotlib.pyplot as plt
from pdb import set_trace as st
import numpy as np
Time = np.array([0,1,2,3,4])
Load = np.array([1,2,3,4,5])
Cell = np.array([6,9,2,5,4])
axialLoadDueToCellPressure = 5.5 * Cell
volumePlotFormat = 'double-wide'
fig = plt.Figure()
fig.set_canvas(plt.gcf().canvas)
ax1 = plt.subplot2grid((3,2), (0,0))
ax1.plot((Time/1000/60),
(Load + axialLoadDueToCellPressure)/6, 'k-')
ax1.plot((Time/1000/60), Cell, 'k--')
fig.savefig("foo3" + ".pdf", format='pdf')
您还可以使用pyplot自己的savefig方法,但我认为,了解Canvas的Figure总体上可能是一件好事.
You could also use pyplot's own savefig method, but I think that the Figure knowing about the Canvas is probably a good thing on the whole.
这篇关于Matplotlib子图-savefig()将不会输出PDF.“无类型"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!