Append each seaborn figure to a PDF inside a for loop

Viewed 499

This is a follow up question to this question Link

I have the following code that produces a figure for each individual person:

# Import pandas library 
import pandas as pd
import numpy as np
# Data
data = [['tom', 10,1], ['nick', 15,1], ['dom', 14,1], ['tom', 15,2], ['nick', 18,2], ['dom', 15,2], ['tom', 17,3]
       , ['nick', 14,3], ['tom',16 ,4], ['dom', 22,3]] 
  
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Name', 'Score','Attempt']) 

# print dataframe. 
df.sort_values(by='Score',ascending=False,inplace=True)

#Plot Images
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn')

for name in df['Name'].unique():
    fig, ax = plt.subplots()
    #df = df.sort_values(by='Score',ascending=False).reset_index(drop=True)
    sub = df[df.Name == name]
    sns.barplot(y='Attempt',x='Score',data=sub, orient='h', ax=ax,order=sub['Attempt'])
    ax.set_title(name.capitalize())

Which gives me:

Ouput

Question:

How can I add to the loop to put each individual figure onto a new page in a pdf. Ideally i can run the code and it produce a 3 page PDF. EG -

Page 1 = Dom
Page 2 = Nick
Page 3 = Tom 

Any help would be much appreciated! Thanks!

1 Answers

I think I have answered my question by doing a bit more searching:

This is the code to plot and save to multiple pages:

#Plot Images and save pdf
import matplotlib.backends.backend_pdf
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn')
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for name in df['Name'].unique():
    fig, ax = plt.subplots()
    sub = df[df.Name == name]
    sns.barplot(y='Attempt',x='Score',data=sub, orient='h', ax=ax,order=sub['Attempt'])
    ax.set_title(name.capitalize())
    pdf.savefig( fig )
pdf.close()
Related