如何按python中的值分组绘制条形图？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (1474)

`df.groupby(['Region','Tier'],sort=True).sum()[['Sales2015','Sales2016']].unstack().plot(kind="bar",width = .8)`

1 个回答

```import numpy as np
import pandas as pd

# The number of demo data count
demo_num = 20

# Regions
regions = ['central', 'east', 'west']
np.random.seed(9)
regions_r = np.random.choice(regions, demo_num)

# Tiers
tiers = ['hi', 'lo', 'mid']
np.random.seed(99)
tiers_r = np.random.choice(tiers, demo_num)

# Sales
sales2015 = np.array(range(demo_num)) * 100
sales2016 = np.array(range(demo_num)) * 200

# Dataframe `df` to store all above
df = pd.DataFrame({'Region': regions_r, 'Tier': tiers_r, 'Sales2015': sales2015, 'Sales2016': sales2016})```

```    Region  Sales2015   Sales2016   Tier
0   west    0           0           lo
1   central 100         200         lo
2   west    200         400         hi
3   east    300         600         lo
4   west    400         800         hi
5   central 500         1000        mid
6   west    600         1200        hi
7   east    700         1400        lo
8   east    800         1600        hi
9   west    900         1800        lo
10  central 1000        2000        mid
11  central 1100        2200        lo
12  west    1200        2400        lo
13  east    1300        2600        hi
14  central 1400        2800        lo
15  east    1500        3000        mid
16  east    1600        3200        hi
17  east    1700        3400        mid
18  central 1800        3600        hi
19  central 1900        3800        hi```

```import matplotlib.pyplot as plt
import pandas as pd

# Summary statistics
df = df.groupby(['Tier', 'Region'], sort=True).sum()[['Sales2015', 'Sales2016']].reset_index(level=1, drop=False)

# Loop over Regions and visualize graphs side by side
regions = df.Region.unique().tolist()
fig, axes = plt.subplots(ncols=len(regions), nrows=1, figsize=(10, 5), sharex=False, sharey=True)

for region, ax in zip(regions, axes.ravel()):
df.loc[df['Region'] == region].plot(ax=ax, kind='bar', title=region)
plt.tight_layout()
plt.show()```