How to save multiple Seaborn plots into single pdf

2019-08-23 10:46发布

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条回答
女痞
2楼-- · 2019-08-23 10:58

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)
查看更多
登录 后发表回答