将数字标签分配给图形时出错

时间:2019-03-23 03:35:51

标签: python pandas matplotlib label

我正在尝试将数字标签值分配给我创建的棒棒糖图。我希望数字标签出现在每个垂直棒棒糖的末尾。我开发了以下脚本,但出现了一个我不明白的错误。

'gap_%'是我感兴趣的变量:

enter image description here

这是我使用的脚本:

ordered_fa_country = country.sort_values(by='gap_%')

my_range_country =range(1,len(country.index)+1)

a4_dims = (10, 12)

f, ax = plt.subplots(figsize=a4_dims)

sns.despine(offset=50)
sns.set_context("talk")

plt.hlines(y=my_range_country, xmin=0, xmax= ordered_fa_country['gap_%'], color='skyblue')
plt.plot(ordered_fa_country['gap_%'], my_range_country, "o")

### Add titles and axis names
plt.yticks(my_range_country, ordered_fa_country['Country'])
plt.title("Gap as % - 2018", loc='left')


for i in my_range_country:
        x = 21 - i
        y = ordered_fa_country['gap_%'][i-1]
        ax.text(y + 2,x,str(y))

这是我得到的错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-109-6f64ab63f14f> in <module>()
     22 for i in my_range_country:
     23         x = 21 - i
---> 24         y = ordered_fa_country['gap_%'][i-1]
     25         ax.text(y + 2,x,str(y))
     26 

~\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    765         key = com._apply_if_callable(key, self)
    766         try:
--> 767             result = self.index.get_value(self, key)
    768 
    769             if not is_scalar(result):

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   3116         try:
   3117             return self._engine.get_value(s, k,
-> 3118                                           tz=getattr(series.dtype, 'tz', None))
   3119         except KeyError as e1:
   3120             if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

发生错误是因为pandas假设您在调用此命令时试图调用列:

 y = ordered_fa_country['gap_%'][i-1]

尝试改用loc表示法。即:

y = ordered_fa_country.loc[(i-1), 'gap_%']

这应该解决它。