Matplotlib: Save figure as file from iPython notebook

Question:

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:

Inline view of figure in iPython notebook


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.

test.png

How can I produce a file from the iPython notebook that looks like the inline view?

Asked By: Martin Preusse

||

Answers:

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.

Answered By: Martin Preusse

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.

Answered By: tbekolay