How to save multiple Seaborn plots into single pdf file

时光怂恿深爱的人放手 提交于 2020-06-28 04:22:20

问题


So I'm trying to save multiple plots that i create in a for loop into a single pdf file. I've searched around on SO and pieced together some code that seems to work except it doesn't save the figures it creates a pdf but without anything in it.

Here's the code to reproduce it:

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

dftest = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),
                    columns=['a', 'b', 'c', 'd', 'e']) 

from matplotlib.backends.backend_pdf import PdfPages

with PdfPages('count.pdf') as pdf_pages:
    df1 = dftest.select_dtypes([np.int, np.float, np.object])
    for i, col in enumerate(df1.columns):
        plt.figure(i)
        countplot = sns.countplot(x=col, data=df1)
        pdf_pages.savefig(countplot.fig)

回答1:


Saving the plt.figure works for me

with PdfPages('count.pdf') as pdf_pages:
    df1 = dftest.select_dtypes([np.int, np.float, np.object])
    for i, col in enumerate(df1.columns):
        figu = plt.figure(i)
        countplot = sns.countplot(x=col, data=df1)
        pdf_pages.savefig(figu)


来源:https://stackoverflow.com/questions/50783151/how-to-save-multiple-seaborn-plots-into-single-pdf-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!