简体   繁体   中英

Multiple files, multiple plots saved to a multipage, single pdf file

I am working with >100 csv files while I am opening and plotting in a loop. My aim is to save each plot on a pdf page and generate a big pdf file with each page containing plot from a single file. I am looking at these examples - (1) and (2) . Trying out combinations using matplotlib.backends.backend_pdf I am unable to get the required result.

Here I re-create my code and the approach I am using:

pdf = PdfPages('alltogther.pdf')
fig, ax = plt.subplots(figsize=(20,10))

for file in glob.glob('path*'):
    df_in=pd.read_csv(file)

    df_d = df_in.resample('d') 
    df_m = df_in.resample('m') 

    y1=df_d['column1']
    y2=df_m['column2'] 
    
    plt.plot(y1,linewidth='2.5') 
    plt.plot(y2,linewidth='2.5')
    pdf.savefig(fig) 
    

With this all the plots are getting superimposed on the same figure and the pdf generated is empty.

You need to move the line

fig, ax = plt.subplots(figsize=(20,10))

Inside the loop, otherwise each iteration will use the same figure instance instead of a new instance. Also note that you need to close the pdf when you are done with it. So the code should be

pdf = PdfPages('alltogther.pdf')

for file in glob.glob('path*'):
    fig, ax = plt.subplots(figsize=(20,10))
    df_in=pd.read_csv(file)

    df_d = df_in.resample('d') 
    df_m = df_in.resample('m') 

    y1=df_d['column1']
    y2=df_m['column2'] 

    plt.plot(y1,linewidth='2.5') 
    plt.plot(y2,linewidth='2.5')
    pdf.savefig(fig) 

pdf.close()

Edit


Complete, self-contained example:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np

pdf = PdfPages('out.pdf')
for i in range(5):
    fig, ax = plt.subplots(figsize=(20, 10))
    plt.plot(np.random.random(10), linestyle=None, marker='.')
    pdf.savefig(fig)

pdf.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM