使用数据框 Matplotlib 的条形图

Bar chart using dataframe Matplotlib

我正在处理具有以下示例数据的 pandas 数据框 (data_agg_clust):

           KPIPred
Cluster 
9-11    125.872327
18-20   120.084786
15-17   112.328802
12-14   109.752560
21-23   106.128234

我想使用 matplotlib 创建条形图:

import matplotlib.pyplot as plt; plt.rcdefaults()

data_agg_clust.plot.bar(x="Cluster", y="KPIPred", rot=70, title="Predicted Volume of impressions");    
plot.show(block=True);

但不幸的是我得到了这个错误:

KeyError                                  Traceback (most recent call last)
~/.pyenv/versions/anaconda3-2021.05/envs/jupiter/lib/python3.10/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

~/.pyenv/versions/anaconda3-2021.05/envs/jupiter/lib/python3.10/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

~/.pyenv/versions/anaconda3-2021.05/envs/jupiter/lib/python3.10/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Cluster'

The above exception was the direct cause of the following exception

它似乎无法识别“Cluster”列。 我该如何解决这个错误?

如果您的数据框的索引有名称,pandas 将通过在列名称下方的一行上打印它来在视觉上区分它。在这种情况下,Cluster 是索引的名称。

最简单的解决方案是单独保留 x:如果您不提供列名,它将默认为索引:

data_agg_clust.plot.bar(y="KPIPred", rot=70, title="Predicted Volume of impressions")

另一种解决方案是调用data_agg_clust.reset_index将索引转换为可用于绘图的列:

data_agg_clust.reset_index().plot.bar(x="Cluster", y="KPIPred", rot=70, title="Predicted Volume of impressions")