对于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()?的建议(代码末尾的for循环),但它看起来不正确。在这里,您将看到输出:
有人可以帮我吗?
答案 0 :(得分:3)
您在ax.text
中使用了错误的变量顺序。使用以下内容。另外,请勿两次使用performance
变量。我现在使用perf
for i, perf in enumerate(performance):
ax.text(i, perf + .25, str(perf), color='black',
ha='center', fontweight='bold')
答案 1 :(得分:1)
i
是x位置的索引,performance
是条形的高度(y位置)。 plt.text
的前两个参数是文本的x和y位置。
for i, performance in enumerate(performance):
ax.text(i, performance + .25, str(performance), color='black', fontweight='bold')
答案 2 :(得分:0)
在您的ax.text调用中,替换:
performance - 0
使用:
i - 0.15
答案 3 :(得分:0)
尝试一下:
xlocs = ax.get_xticks()
for i, performance in enumerate(performance):
ax.text(xlocs[i] - .25, performance + .25, str(performance), color='black', fontweight='bold')