簡體   English   中英

在 python 的條形圖上的條形上方添加值

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

我有以下代碼:

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()

我正在嘗試 label 每個條形圖上方 Y 軸的值(Y 值)。

但是,這段代碼並沒有這樣做。

誰能指出我哪里出錯了?

你快到了; 您只需要將最后一個 for 循環更改為:

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

這將生成這個 plot: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM