I am trying to save a Matplotlib figure as a file from an iPython notebook.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
ax.plot([1,2])
fig.savefig('test.png')
The inline view in the iPython notebook looks good:
The file 'test.png' is almost empty though. It looks like the plot is shifted to the top right, you can see the tick labels '1.0' and '0.0' in the corner.
How can I produce a file from the iPython notebook that looks like the inline view?
Problem solved: add 'bbox_inches='tight'
argument to savefig.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
plt.plot([1,2])
savefig('test.png', bbox_inches='tight')
I don't understand what's happening here, but the file looks like the iPython notebook inline file now. Yay.
tight
tries to minimize that. Its not really related to your issue i think. But only by using tight
, the correct "figure area" is determined, but that doesn't tell (me) much on why it is wrong in the first place - Rutger Kassies 2013-10-09 13:15
Actually, the savefig
is working properly. When you call add_axes
, your list specifies a rectangle: [left, bottom, width, height]
. Since the figure goes from 0 to 1 on both axes with the origin at the bottom left, you're making a rectangle of width and height 1 starting from the very top-right of the figure. You likely want to be doing ax = fig.add_axes([0,0,1,1])
.
I'm not sure why the inline plot doesn't respect where you've placed the axes. If I had to guess, I would say that the inline backend automatically figures out the bounding box and places the inline figure according to that.
.make_axes
; you should let Matplotlib handle that itself. Your example could be done with plt.plot([1,2]); plt.savefig('test.png')
. Adding axes manually is an advanced thing that you would do if you need precise placement of axes; in most cases, however, you should just let Matplotlib do its thing, and use plt.tight_layout()
when things go wrong - tbekolay 2013-10-11 16:17