将循环绘图导出为python中的pdf

问题描述 投票:1回答:1

我设法通过循环下面的df数据框来创建多个子图,但是我无法将所有子图导出到一个pdf中。关于如何生成pdf的任何想法?谢谢

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

d = {'index': ['index1', 'index1', 'index2', 'index2'], 'group': ['gr1', 'gr1','gr2','gr2'], 'targetscore':[15,15,10,10], 'exam':['old','new','old','new'], 'score':[5,6,7,8]}
df = pd.DataFrame(data = d)

for i in range(len(df['group'])):
    subdf = df[df['group'] == df.iloc[i,1]]
    sns.catplot(y = 'score', x = 'group', data = subdf, hue = 'exam', kind = 'bar', 
            row = 'index', col = 'exam', col_order = ['old', 'new'], height = 3, aspect = 2)
    plt.show
python loops matplotlib seaborn
1个回答
0
投票

您可以尝试这样的事情:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages

d = {'index': ['index1', 'index1', 'index2', 'index2'], 'group': ['gr1', 'gr1','gr2','gr2'], 'targetscore':[15,15,10,10], 'exam':['old','new','old','new'], 'score':[5,6,7,8]}
df = pd.DataFrame(data = d)
pp = PdfPages('youpath/foo.pdf')     #create the pdf named 'foo.pdf'
for i in range(len(df['group'])):
    subdf = df[df['group'] == df.iloc[i,1]]
    sns.catplot(y = 'score', x = 'group', data = subdf, hue = 'exam', kind = 'bar', 
            row = 'index', col = 'exam', col_order = ['old', 'new'], height = 3, aspect = 2)
    plt.show
    pp.savefig(plt.gcf())            #Save each figure in pdf


pp.close()                           #close the pdf
© www.soinside.com 2019 - 2024. All rights reserved.