如何在pdf中將多個圖形保存為單獨的頁面?

梅根·馬丁

我有一個循環遍歷 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()
馬納克蘭

將 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() 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何根據 R 中的原始文件名將包含多個數據幀的大列表保存為單獨的 csv

如何在android studio中將Html頁面轉換為Pdf

Pandas 如何將具有多個條目的行拆分為單獨的行?

如何在 Pandas 中將兩個單獨的單元格合併為一個奇異的組合值

如何以 xamarin 形式在單個頁面中播放多個音頻文件

如何從單個數組中的多個頁面獲取鏈接

如何在 PostgreSQL 中將列擴展為單獨的時間步長

如何將異常值作為單獨的彩色標記添加到線圖中

如何在 Drupal 中顯示一個簡單的自定義頁面?

將圖像拆分為許多較小的圖像,並允許來自每個單獨圖像的超鏈接(如圖像映射)

如何在實體框架中將多個實體合二為一(將復雜實體映射為單表)

將 n 個單獨的對象保存到一個類中

將元組列表中的元素排序為兩個單獨的列表

Matlab:如何通過鼠標單擊(使用“ButtonDownFcn”)將多個變量點從繪圖中保存到工作區中?

使用 Pandas 將兩個獨立單元格中的值轉換為一個單元格

將包含多個名稱和日期的日期向量分離為 R 中的單獨名稱和日期向量

如何在條形圖中添加單個標記

如何在另一個頁面(收藏夾頁面)的另一個列表中的共享首選項中顯示保存的列表?

如何為循環中的每個按鈕分配一個單獨的值?

如何在源文件中將字符“E”表示為單個字節?

如何在python中將字典鍵值從列表更改為單個int或float?

如何在 C++ 中將許多單選按鈕分為 3 組?

如何在 ggplot2 中將圖例鍵字形的形狀更改為六邊形?

試圖保存評論,但應用程序將我重定向到一個空頁面

如何在 R 中更改多個堆疊條形圖中的顏色?

如何在SPSS中將多個案例合併為一個?

兩個單獨的句子垂直放置在頁面中央,跨屏幕大小,不重疊

如何在閃亮的儀表板中引用多個 DiagrammeR GraphViz 圖形

在 R markdown 中,如何防止來自非緩存塊的圖被單獨保存?