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

Question:

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.775×0.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?

Asked By: Yulia Kentieva

||

Answers:

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()
Answered By: chris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.