[英]Matplotlib subplots figure - savefig() won't output PDF. “NoneType” error
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')
. 问题出现在最后一行,
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')
The problem is with the canvas, when using the fig.savefig() method. 当使用fig.savefig()方法时,问题出在canvas上。 At this point pyplot is attached to a Canvas, but your figure does not.
此时pyplot附加到Canvas,但你的数字却没有。 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.
如果您将图显式附加到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')
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. 你也可以使用pyplot自己的savefig方法,但我认为知道Canvas的图可能是一件好事。
fig.savefig()
is the problem. fig.savefig()
就是问题所在。 You need to use plt.savefig()
, the fig
class has no savefig()
attribute. 你需要使用
plt.savefig()
, fig
类没有savefig()
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.