[英]matplotlib grouped bars in a bar graph
I'm playing with matplotlib and pandas to create a bar graph. 我正在玩matplotlib和熊猫来创建条形图。 I have a dataframe of world cup teams and here is what
df.head()
shows 我有世界杯球队的数据
df.head()
,这是df.head()
显示的内容
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. 我想创建一个条形图,其中每个条形都是一个唯一的
team
,并且一group
中的每个团队都被紧密地绘制在一起,并且各个组之间的距离明显不同。 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))
and for visual purposes, I want it to look like this: 出于视觉目的,我希望它看起来像这样:
The most straightforward way to do this is to reset the index of your groupby data frame and use seaborn's factorplot. 最简单的方法是重置groupby数据框的索引并使用seaborn的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.