Reputation: 157
I have not used matplotlib before- i have downloaded the libary and read the documentation. I am trying to display the value on top of the bar using the code below. However, the value does not display
import numpy as np
import matplotlib.pyplot as plt
data = [ ("data1", 34), ("data5", 22),
("data12", 11), ( "data8", 28),
("data53", 57), ( "data11", 39),
("data12", 23), ( "data15", 98)]
N = len(data)
x = np.arange(1,N+1)
y = [ num for (s, num) in data ]
labels = [ s for (s, num) in data ]
width = 1
bar1 = plt.bar( x, y, width, color="y" )
plt.ylabel( 'Intensity' )
plt.xticks(x + width/2.0, labels )
for x, y in zip(x, y):
plt.annotate("%i" % y, (x, y + 200), ha= 'center')
plt.show()
Any help is greatly appreciated
Upvotes: 4
Views: 11876
Reputation: 53678
Your issue is simply that the position of your annotations is way above your current y-axis limits, due to you adding 200 to the y-position.
import numpy as np
import matplotlib.pyplot as plt
data = [ ("data1", 34), ("data5", 22),
("data12", 11), ( "data8", 28),
("data53", 57), ( "data11", 39),
("data12", 23), ( "data15", 98)]
N = len(data)
x = np.arange(1,N+1)
y = [ num for (s, num) in data ]
labels = [ s for (s, num) in data ]
width = 1
bar1 = plt.bar( x, y, width, color="y" )
plt.ylabel( 'Intensity' )
plt.xticks(x + width/2.0, labels )
y_shift = 5
x_shift = width/2.0
for x, y in zip(x, y):
plt.annotate("%i" % y, (x + x_shift, y + y_shift), ha= 'center')
plt.ylim(0,110)
plt.show()
Simply changing the vertical offset to a more reasonable number (chosen above as y_shift = 5
) fixes the height issue, but you also need to add width/2.0
to the x-position to get the text in the centre of the bar (assuming that's what you want). I've also added plt.ylim(0,110)
to the end to shift the y-limits a bit to show the number for the biggest bar.
Upvotes: 5