简体   繁体   English

在 python 的条形图上的条形上方添加值

[英]Add values above bars on a bar chart in python

I have the following code below:我有以下代码:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

languages =['Python', 'SQL', 'Java', 'C++', 'JavaScript']
pos = np.arange(len(languages))
popularity = [56, 39, 34, 34, 29]

bars = plt.bar(pos, popularity, align='center', linewidth=0, color='lightslategrey')
bars[0].set_color('#1F77B4')

plt.xticks(pos, languages, alpha=0.8)

plt.ylabel("")
plt.title('Top 5 Languages for Math & Data \nby % popularity on Stack Overflow', alpha=0.8)

plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

for spine in plt.gca().spines.values():
    spine.set_visible(False)

for index, value in enumerate(str(popularity)): 
    plt.text(index,value,str(popularity))

plt.show()

I am trying to label the values from the Y-axis above each bar (the Y-values).我正在尝试 label 每个条形图上方 Y 轴的值(Y 值)。

However, this code is not doing that.但是,这段代码并没有这样做。

Could anybody point out to me where I am going wrong?谁能指出我哪里出错了?

You are almost there;你快到了; You only need to change the last for loop to be like so:您只需要将最后一个 for 循环更改为:

...
...
for index, value in enumerate(popularity):
    plt.text(index,value, str(value))
plt.show()

which will generate this plot:这将生成这个 plot: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM