1

I have the following code for a barchart in 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()

I would like to have values above the bars. I use the suggestion (for loop at the end of my code) from How to display the value of the bar on each bar with pyplot.barh()? but it does not look correct. Here you see the output: enter image description here

Can anyone help me on that?

PeterBe
  • 700
  • 1
  • 17
  • 37

4 Answers4

3

You used wrong order of variables in ax.text. Use the following. Also, don't use performance variable twice. I used perf now

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

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
1

i is the index of x position, performance is height of the bar (y position). The first two parameters of plt.text are x and y positions of the text.

for i, performance in enumerate(performance):
    ax.text(i, performance + .25, str(performance), color='black', fontweight='bold')
Ardweaden
  • 857
  • 9
  • 23
0

In your ax.text call, replace:

performance - 0

With:

i - 0.15
Thomas Schillaci
  • 2,348
  • 1
  • 7
  • 19
0

Try this:

xlocs = ax.get_xticks()

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