【发布时间】:2020-05-25 09:23:34
【问题描述】:
假设我有一个名为“市场”的数据框,其中包含我的交易的完整数据库。我按每个月和产品对其进行分组,因此我得到每个产品/月的销售额总和(美元)
test=market.groupby(['Product','Month']).sum()['Sales'].unstack()
test
上面的结果是这样的
month/product 1 2 3 4 5 6 7 8 9 10 11 12
milk 12 13 12 13 21 21 9 10 15 17 16 20
bread 15 13 13 12 25 24 11 5 13 13 17 14
rice 12 13 15 13 21 21 9 10 19 11 16 25
coffee 12 13 12 16 25 23 11 20 15 14 11 15
tea 15 13 12 13 25 24 11 5 13 8 17 19
如何制作包含堆叠产品销售额的图表?
x 轴 = 每个产品的累积销售额月份
y 轴 = 销售额
我已经做了什么:
第一次尝试:
fig, sumbu = plt.subplots(figsize=(5,3))
graph=test.plot.bar(stacked='True', ax=sumbu)
plt.xlabel('Month', fontsize='12', color='red')
plt.ylabel('Sales', fontsize='12', color='red')
plt.xticks(rotation=45, size=8)
plt.show(graph)
它运行但 X 轴是产品(我预计月份)
第二次尝试:
fig, sumbu = plt.subplots(figsize=(5,3))
graph=test.plot.bar(x='Month', y='Sales', stacked=True, ax=sumbu)
plt.xlabel('Month', fontsize='12', color='red')
plt.ylabel('Sales', fontsize='12', color='red')
plt.xticks(rotation=45, size=8)
plt.show(graph)
"KeyError: '月'
【问题讨论】:
-
测试数据框中可以找到哪些列?您是否尝试过通过 test.info() 查看它们?也许这可以帮助您找到正确的名称。此外,您可以尝试转置测试数据框以将月份作为行来绘制。
-
嘿,我尝试了您的建议来转置该数据框,它按我的意愿运行良好。 (每月堆叠产品销售额)
标签: python dataframe matplotlib group-by data-visualization