【问题标题】:Add values above bars on a bar chart in python在python中的条形图上的条形上方添加值
【发布时间】:2020-09-14 12:48:47
【问题描述】:

我有以下代码:

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

我正在尝试从每个条形图上方的 Y 轴标记值(Y 值)。

但是,这段代码并没有这样做。

谁能指出我哪里出错了?

【问题讨论】:

  • 查看this question中的解决方案。
  • @QuangHoang 我快到了,请参阅下面的解决方案。
  • 添加 ha='center' 以使您的价值观居中。

标签: python numpy matplotlib graph visualization


【解决方案1】:

你快到了;您只需将最后一个 for 循环更改为如下所示:

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

这将产生这个情节:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多