0

I am trying to plot a pandas dataframe (result_m) using the pandas plotting function, but when I try to save the figure using savefig but it returns a blank pdf. It plots fine in the notebook window. Not sure what I'm doing wrong

fig = plt.figure()

ax = result_m.plot( kind='line',  figsize=(20, 10),fontsize=15)
ax.set_title('Harkins Slough Diversions',fontsize= 20) 
ax.set_xlabel( "Date",fontsize=18)
ax.set_ylabel("cubic meters",fontsize=18)
plt.legend(fontsize=15)

fig.savefig(os.path.join(outPath4,'plot_fig.pdf'))
user11958450
  • 109
  • 1
  • 7
  • Please take a look at this, https://stackoverflow.com/questions/51203839/python-saving-empty-plot/51203929, and this https://stackoverflow.com/questions/9012487/matplotlib-pyplot-savefig-outputs-blank-image – Akib Rhast May 27 '20 at 01:19
  • Does this answer your question? [Matplotlib (pyplot) savefig outputs blank image](https://stackoverflow.com/questions/9012487/matplotlib-pyplot-savefig-outputs-blank-image) – Akib Rhast May 27 '20 at 01:19
  • @AkibRhast I think this is a slightly different question, since this involves pandas plots not being added to a matplotlib figure by default, whereas those posts mostly deal with matplotlib directly, and how plt.show clears the figure. – Michael Delgado May 27 '20 at 02:27
  • I see, I see I google fig.savefig() and it brought up matplotlib.. so i figured that is what he is using? @MichaelDelgado So is his savefig pandas? – Akib Rhast May 27 '20 at 02:57
  • The OP is using matplotlib.pyplot.Figure.savefig, which is a matplotlib method, but the plot they are trying to save is being generated using pandas.DataFrame.plot. – Michael Delgado May 27 '20 at 05:12

1 Answers1

1

The problem is that the plot you create is not on the figure you create (and save). In the second line:

ax = result_m.plot( kind='line',  figsize=(20, 10),fontsize=15)

pandas creates a new figure, since you did not supply an axis (ax) argument. See the pandas docs on plotting to specific subplots.

You could fix this by either skipping the figure creation step, then getting the figure pandas creates from the axis object:

ax = result_m.plot( kind='line',  figsize=(20, 10),fontsize=15)
fig = ax.figure

or by adding the plot to the figure you created, by first creating a subplot:

fig = plt.figure(size=(20, 10))
ax = fig.add_subplot(111)
ax = result_m.plot( kind='line',  fontsize=15, ax=ax)

Note that in this option, define the figure's size attribute when you create the figure, rather than by passing figsize to DataFrame.plot.

Michael Delgado
  • 13,789
  • 3
  • 29
  • 54