Yulia Kentieva
Yulia Kentieva

Reputation: 720

Save figure from a for loop in one pdf file in python

I am trying to save scatter plots from a list of dataframes in one pdf file using this:

pdf = matplotlib.backends.backend_pdf.PdfPages("./output.pdf")
for df in list_degs_dfs:
    dfplt = df.plot.scatter("DEratio", "MI_scaled")
    pdf.savefig(dfplt)
pdf.close()

But I get this error:

ValueError: No figure AxesSubplot(0.125,0.11;0.775x0.77)

I thought it can be an issue with converting the plots to matplotlib figure and tried this:

import matplotlib.pyplot as plt
pdf = matplotlib.backends.backend_pdf.PdfPages("./output.pdf")
for df in list_degs_dfs:
    dfplt = df.plot.scatter("DEratio", "MI_scaled")
    dfplt = plt.figure(dfplt)
    pdf.savefig(dfplt.Figure)
pdf.close()

and got this:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'AxesSubplot'

How to save all dfplt figrues from all df dataframes from a list of dataframes in one file?

Upvotes: 0

Views: 877

Answers (1)

chris
chris

Reputation: 1322

savefig should not take any arguments, it will save the currently active figure handle.

pdf = matplotlib.backends.backend_pdf.PdfPages("./output.pdf")
for df in list_degs_dfs:
    dfplt = df.plot.scatter("DEratio", "MI_scaled")
    pdf.savefig() # saves the active handle
pdf.close()

Upvotes: 2

Related Questions