简体   繁体   English

多个文件、多个绘图保存到多页、单个 pdf 文件

[英]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.在循环打开和绘图时,我正在处理 >100 个 csv 文件。 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.我的目标是将每个图保存在 pdf 页面上,并生成一个大的 pdf 文件,每个页面都包含来自单个文件的图。 I am looking at these examples - (1) and (2) .我正在查看这些示例 - (1)(2) Trying out combinations using matplotlib.backends.backend_pdf I am unable to get the required result.使用matplotlib.backends.backend_pdf尝试组合我无法获得所需的结果。

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.有了这个,所有的图都叠加在同一个图上,生成的pdf是空的。

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.另请注意,完成后需要关闭pdf。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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