python - 通过在 python 中对值进行分组来绘制条形图

标签 python pandas matplotlib

我想绘制一个条形图,我需要在其中比较两个区域相对于RegionTier的销售额。

我实现了以下代码:

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

enter image description here

但我想同时实现 2015 年和 2016 年 Tier 的销售, 例如,在 x 轴上,xticks 应类似于 2015 年和 2016 年的高销售额等。 enter image description here

最佳答案

数据生成:我使用以下代码随机生成您的数据:

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()
<小时/>

结果:现在图表如下所示。我还没有优化字体大小等.. Output

希望这有帮助。

关于python - 通过在 python 中对值进行分组来绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50884859/

相关文章:

python - pandas 条形图结合线图显示了从 1970 年开始的时间轴

python - pandas df 中的多列分组和计数总和

python - 从数据框列名称中删除句点 (.)

python - Pandas 每 N 行将数据框 reshape 为列

python - 我如何选择 pandas 中时间范围的数据

python - 当 matplotlib 工作正常时出现错误 : 'no module named ' matplotlib. style'

python - Sqlalchemy mySQL 优化查询

Python gearman 基本示例错误

python - 如何使用 R studio 导入 Pandas

Matplotlib 表 : individual column width