Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'). 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')
like image 242
nivek Avatar asked Feb 20 '14 15:02

nivek


2 Answers

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')

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.

like image 71
Weir_Doe Avatar answered Oct 08 '22 20:10

Weir_Doe


fig.savefig() is the problem. You need to use plt.savefig(), the fig class has no savefig() attribute.

like image 27
pseudocubic Avatar answered Oct 08 '22 20:10

pseudocubic