SOK
SOK

Reputation: 1792

How to plot a barchart by pandas groupby and then loop for all unique values

I have the following data which has a persons name, score and what attempt number it was:

# 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 

    Name    Score   Attempt
0   tom     10  1
1   nick    15  1
2   dom     14  1
3   tom     15  2
4   nick    18  2
5   dom     15  2
6   tom     17  3
7   nick    14  3
8   tom     16  4
9   dom     22  3

I am hoping to plot a seaborn horizontal bar plot for each unique Name which has Score as the value and the axis as the Attempt number (category) and then create a loop so that it produces a 3 page PDF for each person. What I don't quite understand is how to:

a) plot by a groupby - do i need to make multiple sliced dataframes?

b) make it in a loop to produced multiple pages for a PDF.

Any help would be much appreciated! Thanks!

Upvotes: 0

Views: 745

Answers (1)

Tom
Tom

Reputation: 8800

Here is a loop to plot the data for each name as a separate graph:

plt.style.use('seaborn')

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)
    ax.set_title(name.capitalize())

One of the three plots:

enter image description here

I would move the PDF part of your question to a new post, as it is kind of vague what your are asking for (what's going to fill 3 pages?), and it seems like a separate issue from making the plots.

But note that you can save graphs straight into a (1-page) PDF:

#in the loop
    fig.savefig(name+'.pdf')

Upvotes: 2

Related Questions