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()
It seems easy for me that use plt.savefig()
function after plot()
function:
import matplotlib.pyplot as plt
dtf = pd.DataFrame.from_records(d,columns=h)
dtf.plot()
plt.savefig('~/Documents/output.png')
So I'm not entirely sure why this works, but it saves an image with my plot:
dtf = pd.DataFrame.from_records(d,columns=h)
dtf2.plot()
fig = plt.gcf()
fig.savefig('output.png')
I'm guessing that the last snippet from my original post saved blank because the figure was never getting the axes generated by pandas. With the above code, the figure object is returned from some magic global state by the gcf() call (get current figure), which automagically bakes in axes plotted in the line above.
this may be a simpler approach:
(DesiredFigure).get_figure().savefig('figure_name.png')
i.e.
dfcorr.hist(bins=50).get_figure().savefig('correlation_histogram.png')
You can use ax.figure.savefig()
, as suggested in a comment on the question:
import pandas as pd
df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')
This has no practical benefit over ax.get_figure().savefig()
as suggested in other answers, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
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")