【问题标题】:How to save multiple graphs as separate pages in a pdf?如何将多个图形保存为 pdf 中的单独页面?
【发布时间】:2022-01-01 14:26:23
【问题描述】:

我有一个循环遍历 50 个数据帧并为每个数据帧计算一个名为 p90_annual 的变量。在这个循环中,我想将p90_annual 绘制为pdf 中的一个页面,其中每个数据帧的每个页面都是p90_annual。 (我想要一个 50 页的 pdf,其中每一页是每个数据帧的 p90_annual 的图)我目前正在使用:

with PdfPages('90thPercentile.pdf') as pdf:
    plt.figure
    plt.plot(p90_annual)
    plt.title(j)
    plt.ylabel('Days Above 90th Percentile')
    pdf.savefig()
    plt.close()

当我这样做时,我只会得到一个页面,其中绘制了p90_annual 的最后一个实例。如何修改它,以便在循环时为 p90_annual 的每个实例添加一个新页面?

对于上下文...下面是我试图让它在其中工作的更大循环

# Huge Loop
for j in TempDict:
    #Make Baseline
    df=TempDict[j]
    df=pd.to_numeric(df.tmax, errors='coerce')
    mask = (df.index >= '1900-01-01') & (df.index <= '1940-12-31')
    Baseline=df.loc[mask]
    Tmax=Baseline.astype(np.float)
    Index=Baseline.index
    DailyBase=pd.DataFrame(data={'date':Index,'tmax':Tmax})
    #pivot dataframe
    DailyBase['year']=DailyBase.date.dt.year
    DailyBase['day']=DailyBase.date.dt.strftime('%m-%d')
    BaseResult=DailyBase[DailyBase.day!='02-29'].pivot(index='year',columns='day',values='tmax')
    #Calculate Percentiles
    BaseResult.index=list(range(1,42))
    BaseResult.insert(0,'12-31_',BaseResult['12-31'])
    BaseResult.insert(0,'12-30_',BaseResult['12-30'])
    BaseResult['01-01_'] = BaseResult['01-01']
    BaseResult['01-02_'] = BaseResult['01-02']
    p90_todict = {}
    for i in range(len(BaseResult.columns)-4):
        index = i+2
        p90_todict[BaseResult.columns[index]] = np.quantile(BaseResult.iloc[:,index-2:index+3].dropna(),.9)
    np.quantile(BaseResult.iloc[:,index-2:index+3].dropna(),.98)
    #Make POR dataframe
    #pull tmax and dates from original ACIS data
    FullTmax=df.astype(np.float)
    FullIndex=df.index
    #create and rotate data frame
    DailyPOR=pd.DataFrame(data={'date':FullIndex,'tmax':FullTmax})
    DailyPOR['year']=DailyPOR.date.dt.year
    DailyPOR['day']=DailyPOR.date.dt.strftime('%m-%d')
    PORResult=DailyPOR[DailyPOR.day!='02-29'].pivot(index='year',columns='day',values='tmax')
    #Compare POR and baseline
    import copy
    #eliminate leap years from POR daily data
    noleap_DailyPOR = copy.copy(DailyPOR[DailyPOR.day != '02-29'])
    noleap_DailyPOR.index = noleap_DailyPOR.date
    #Use only winter months
    only_winter = noleap_DailyPOR[(noleap_DailyPOR.index.month >= 12) | (noleap_DailyPOR.index.month <= 2)]
    #set results to 0 for counts
    p90results = pd.DataFrame(index = only_winter.date)
    p90results['above90'] = 0
    #Compare POR and percentiles
    for index, row in only_winter.iterrows():
        if row.tmax > p90_todict[row.day]:
            p90results.loc[row.date,'above90'] = 1
    #Sum annual counts above percentiles
    p90_annual=p90results.groupby(p90results.index.year).sum()
    with PdfPages('90thPercentile.pdf') as pdf:
        plt.rcParams['text.usetex'] = False
        plt.figure
        plt.plot(p90_annual)
        plt.title(j)
        plt.ylabel('Days Above 90th Percentile')
        pdf.savefig()
        plt.close()

【问题讨论】:

  • 不幸的是,没有,我尝试添加 ``` with PdfPages('90thPercentile.pdf') as pdf: plt.rcParams['text.usetex'] = False plt.figure plt.plot(p90_annual) plt.title(j) plt.ylabel('Days Above 90th Percentile') pdf.savefig() plt.close()``` 但我仍然只得到 p90_annual 的最后一个实例
  • 我在这里提供了一个答案,方法略有不同;可能有用/有趣:stackoverflow.com/questions/38938454/…

标签: python pandas numpy matplotlib pdfpages


【解决方案1】:

将 for 循环放入 with PDFPages() as pdf: 会有所帮助:

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


p90_annual = pd.DataFrame({"data": [19,20,13]})

with PdfPages('90thPercentile.pdf') as pdf:
  for i in range(0,50):
    plt.figure
    plt.plot(p90_annual)
    plt.title(i)
    plt.ylabel('Days Above 90th Percentile')
    pdf.savefig()
  plt.close()

更新: 我想我说得不够清楚,关键是把with PDFPages() as pdf:移到你的循环之外,然后一切都将是文件。

with PdfPages('90thPercentile.pdf') as pdf:
  #your loop here
  for j in TempDict:
    ....
    plt.figure
    plt.plot(p90_annual)
    plt.title(i)
    plt.ylabel('Days Above 90th Percentile')
    pdf.savefig()
    plt.close() 

【讨论】:

  • 这不起作用,因为 p90annual 处于更大的 for 循环中。对于上下文,我将在上面发布我的完整循环
  • 您好,我检查了您的更新,将with PdfPages('90thPercentile.pdf') as pdf: 移至for j in TempDict: 上方即可。检查我的更新
猜你喜欢
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 2010-11-26
  • 2014-03-03
  • 2023-03-29
  • 2014-01-12
相关资源
最近更新 更多