I'm playing with matplotlib and pandas to create a bar graph. I have a dataframe of world cup teams and here is what df.head()
shows
I want to create a bar graph, where each bar is a unique team
, and each team in a group
are graphed close together, with unique groups between a noticeable distance apart. Here is what I currently have:
caps_per_team_per_group = df.groupby(['group', 'team']).Caps.sum()
caps_per_team_per_group.plot(kind='bar', figsize=(15,5))
The most straightforward way to do this is to reset the index of your groupby data frame and use seaborn's factorplot.
import numpy as np
import pandas as pd
import seaborn as sns
# Setting up
group_A = ['Egypt', 'Russia', 'Uruguay', 'Saudi Arabia']
group_B = ['Spain', 'Portugal', 'Iran', 'Morocco']
group_C = ['France', 'Denmark', 'Australia', 'Peru']
team = group_A + group_B + group_C
group =['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C']
caps = np.random.randint(5, 50, 12)
caps_per_team_per_group = pd.DataFrame({ 'Caps': caps}, index=pd.MultiIndex.from_tuples(list(zip(group, team)), names=['Group', 'Team']))
# Reset index and plot
caps_per_team_per_group.reset_index(inplace=True)
g = sns.factorplot(x="Group", y="Caps", hue='Team', data=caps_per_team_per_group, kind="bar", palette="muted")
n [47]: caps_per_team_per_group
Out[47]:
Caps
Group Team
A Egypt 43
Russia 39
Uruguay 20
Saudi Arabia 49
B Spain 6
Portugal 8
Iran 32
Morocco 11
C France 14
Denmark 41
Australia 29
Peru 8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.