使用pyplot和Pandas在Barchart的条形图中添加标签失败

时间:2018-06-28 04:33:15

标签: python-3.x pandas matplotlib label bar-chart

我的目的是创建一个条形图,并通过在条形图中插入它们对应的值来对其进行注释。

我的代码出了点问题,但我不知道什么:

我的数据:

top_15

         Total
Country 
China   228100
India   183289
Pakistan    92869
Philippines 81537
United Kingdom of Great Britain and Northern Ireland    60356
Republic of Korea   49094
Iran (Islamic Republic of)  45713
United States of America    38151
Sri Lanka   35156
Romania 33823
Russian Federation  28283
France  25550
Afghanistan 21941
Ukraine 21113
Morocco 21092

我的代码:

top_15.plot(kind='barh', figsize=(10, 10), color='steelblue')
plt.xlabel('Number of Immigrants')
plt.title('Top 15 Conuntries Contributing to the Immigration to Canada between 1980 - 2013')

# annotate value labels to each country
for index, value in enumerate(top_15.loc[:,'Total']): 
    label = format(int(value), ',') # format int with commas

    # place text at the end of bar (subtracting 47000 from x, and 0.1 from y to make it fit within the bar)
    plt.annotate(label, xy=(value - 47000, index - 0.10), color='white')

plt.show()

输出:

enter image description here

您的建议将不胜感激。

3 个答案:

答案 0 :(得分:0)

您可以使用xy确定注释的位置。您正在使用value - 47000为每个国家/地区设置不同的值。这也会带来一些负值(在图形外部)。要在小节的开头显示所有这些内容,您可以使用固定值,例如:

xy=(1000, index - 0.10)

或者一个大于最小值的值(在这种情况下,它将位于小节的末尾):

 xy=(value - 21000, index - 0.10)

答案 1 :(得分:0)

不确定要查找的内容,但是请尝试更改行: plt.annotate(label, xy=(value - 47000, index - 0.10), color='white')

至: plt.text(value, index, label, ha='right', va='center')

答案 2 :(得分:0)

您的代码的问题是您要减去的x值,即47000(大于最小值),只需将该数字减小为47(或大于最小值的任何数字)即可使用。如果背景为白色,也可以将文本的颜色更改为黑色

% %matplotlib inline
import matplotlib.pyplot as plt
top_15.plot(kind='barh', figsize=(10, 10), color='steelblue')
plt.xlabel('Number of Immigrants')
plt.title('Top 15 Conuntries Contributing to the Immigration to Canada between 1980 - 2013')

# annotate value labels to each country
for index, value in enumerate(top_15.loc[:,'Total']): 
    label = format(int(value), ',') # format int with commas

    # place text at the end of bar (subtracting 47000 from x, and 0.1 from y to make it fit within the bar)
    plt.annotate(label, xy=(value - 47, index - 0.10), color='black')

plt.show()

enter image description here

替代方法:

% matplotlib inline
import matplotlib.pyplot as plt
ax = df.plot(kind='barh', figsize=(15,10),color="steelblue", fontsize=13);

ax.set_title("Top 15 Conuntries Contributing to the Immigration to Canada between 1980 - 2013", fontsize=18)
ax.set_xlabel("Number of Immigrants", fontsize=18);

for i in ax.patches:
    # get_width pulls left or right; get_y pushes up or down
    ax.text(i.get_width()+.1, i.get_y()+.31, \
            str(round((i.get_width()), 2)), fontsize=10, color='black')