Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: Save figure as file from iPython notebook

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?

like image 618
Martin Preusse Avatar asked Oct 09 '13 11:10

Martin Preusse


People also ask

How do I save a figure to a file in Matplotlib?

Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.


1 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.

like image 67
Martin Preusse Avatar answered Sep 17 '22 17:09

Martin Preusse