繁体   English   中英

Matplotlib 中条形图中条形图上方的值

[英]Values above the bars in a barchart in Matplotlib

我有以下代码用于 matplotlib 中的条形图

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018')
y_pos = np.arange(len(objects))
performance = [8.5,9.1,9.7, 10.6, 11.4, 12.6, 13.2, 13.4, 14.7, 15.4, 16.2, 16.7, 17.0, 17.5, 18.0]

fig, ax = plt.subplots(figsize=(18,5))



plt.bar(y_pos, performance, align='center', alpha=0.5, color="green")
plt.xticks(y_pos, objects)
plt.ylim(0, 20)
plt.ylabel('Share in %',  fontsize = 16)
plt.xlim(-0.6, len(objects) - 0.4)
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('Share_Of_Renewables_Europe.png', edgecolor='black', dpi=400, bbox_inches='tight',
           figsize=(18,5) )

for i, performance in enumerate(performance):
    ax.text(performance - 0, i + .25, str(performance), color='black', fontweight='bold')

plt.show()

我希望有高于条形的值。 我使用了来自How to display the value of the bar on each bar with pyplot.barh()? 但它看起来不正确。 在这里您可以看到输出: 在此处输入图片说明

任何人都可以帮助我吗?

您在ax.text使用了错误的变量ax.text 使用以下内容。 另外,不要两次使用performance变量。 我现在用perf

for i, perf in enumerate(performance):
    ax.text(i, perf + .25, str(perf), color='black', 
            ha='center', fontweight='bold')

在此处输入图片说明

i是 x 位置的索引, performance是条形(y 位置)的高度。 plt.text的前两个参数是plt.text的 x 和 y 位置。

for i, performance in enumerate(performance):
    ax.text(i, performance + .25, str(performance), color='black', fontweight='bold')

在 ax.text 调用中,替换:

performance - 0

和:

i - 0.15

尝试这个:

xlocs = ax.get_xticks()

for i, performance in enumerate(performance):
    ax.text(xlocs[i] - .25, performance + .25, str(performance), color='black', fontweight='bold')

暂无
暂无

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

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