Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

I'm using pandas to generate a plot from a dataframe, which I would like to save to a file:

dtf = pd.DataFrame.from_records(d,columns=h) fig = plt.figure() ax = dtf2.plot() ax = fig.add_subplot(ax) fig.savefig('~/Documents/output.png') 

It seems like the last line, using matplotlib's savefig, should do the trick. But that code produces the following error:

Traceback (most recent call last):   File "./testgraph.py", line 76, in <module>     ax = fig.add_subplot(ax)   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 890, in add_subplot     assert(a.get_figure() is self) AssertionError 

Alternatively, trying to call savefig directly on the plot also errors out:

dtf2.plot().savefig('~/Documents/output.png')     File "./testgraph.py", line 79, in <module>     dtf2.plot().savefig('~/Documents/output.png') AttributeError: 'AxesSubplot' object has no attribute 'savefig' 

I think I need to somehow add the subplot returned by plot() to a figure in order to use savefig. I also wonder if perhaps this has to do with the magic behind the AxesSubPlot class.

EDIT:

the following works (raising no error), but leaves me with a blank page image....

fig = plt.figure() dtf2.plot() fig.savefig('output.png') 

EDIT 2: The below code works fine as well

dtf2.plot().get_figure().savefig('output.png') 
like image 650
bhoward Avatar asked Oct 24 '13 01:10

bhoward


People also ask

How do you save a plot in Python without it showing?

We can simply save plots generated from Matplotlib using savefig() and imsave() methods. If we are in interactive mode, the plot might get displayed. To avoid the display of plot we use close() and ioff() methods.

How do I use Savefig in Matplotlib?

Saving a plot on your disk as an image file 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

The gcf method is depricated in V 0.14, The below code works for me:

plot = dtf.plot() fig = plot.get_figure() fig.savefig("output.png") 
like image 132
Wael Ben Zid El Guebsi Avatar answered Sep 30 '22 14:09

Wael Ben Zid El Guebsi