Seaborn plots saving in a single pdf using for loop

Question:

I am trying to save multiple seaborn plots created in a for loop into a single pdf. Here is the code I have tried:

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

pdf = PdfPages('Histogram.pdf')


file='LD25_Percent_Error.txt'
df_main=pd.read_csv(file, delimiter='t')
df_clean=df_main.loc[abs(df_main['obs_vel']) >=0.5]

for i,sim in enumerate(df_clean.sim.unique()):
    fig = plt.figure(i,figsize=(8,4))

    df1=df_clean.loc[df_clean['sim'] == sim] 

    sns.displot(df1, x='% error',kde=True) 
    plt.xlabel("% Error")
    plt.ylabel("Count")
    plt.title('Simulation: %s' % (sim))
    plt.tight_layout()
    

    plt.savefig("sim_{0}.png".format(sim),bbox_inches='tight',dpi=150)
    
    pdf.savefig(fig)
    

pdf.close() 

It saves all the *.png figures seperately but in the pdf it saves all but the first plot. It basically keeps the very first plot empty and saves all the other plots.
Here is the input file LD25_Percent_Error.txt

Asked By: ZVY545

||

Answers:

The problem with sns.displot function. As seen in this answer you can’t specify the axes of the displot. In this case, it draws the chart on the next figure. Therefore you miss the last chart, and your first figure will be empty. You can use histplot:

sns.histplot(df1, x='% error',kde=True,ax=plt.gca()) 
Answered By: Enes Altınışık