【问题标题】:"Keyerror" when make stack graph with matplotlib使用 matplotlib 制作堆栈图时出现“Keyerror”
【发布时间】: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() 查看它们?也许这可以帮助您找到正确的名称。此外,您可以尝试转置测试数据框以将月份作为行来绘制。
  • 另外,请查看answer,也许它会对您有所帮助。这表示要绘制 market.groupby(['Product','Month']).sum()['Sales'].unstack().plot.bar(rot=0) 或检查answer,或@987654323 @
  • 嘿,我尝试了您的建议来转置该数据框,它按我的意愿运行良好。 (每月堆叠产品销售额)

标签: python dataframe matplotlib group-by data-visualization


【解决方案1】:

经过2小时的反复试验,我找到了答案。 您必须转置您的数据框

test2=test.transpose()

fig, sumbu = plt.subplots(figsize=(5,3))
graph=test2.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)

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2013-07-24
    • 2015-04-27
    • 2012-05-29
    • 2016-03-11
    • 2021-12-25
    • 2018-02-22
    • 2021-02-18
    相关资源
    最近更新 更多