2
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt

data = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 5]

ax = plt.axes()
ax.text(0.25, 3, 'Firts label', rotation=90)
ax.text(1.25, 3, 'The Second One', rotation=90)
ax.text(2.25, 3, 'Labes', rotation=90)
ax.text(3.25, 3, 'Foo', rotation=90)
ax.text(4.25, 3, 'Bar', rotation=90)

plt.bar(range(len(data)), data, color='g')
plt.show()

enter image description here

I have a list of labels for each bar. If I create a function that take bars data as arguments, how to align the labels to the top of the bar dynamically?

Community
  • 1
  • 1
khex
  • 2,778
  • 6
  • 32
  • 56
  • 2
    Have you looked into the `verticalalignment` or `va` keyword? Give it a try. – Ajean Jul 06 '15 at 19:57
  • 1
    see [this](http://stackoverflow.com/questions/30228069/how-to-display-the-value-of-the-bar-on-each-bar-with-pyplot-barh/30229062#30229062) (horizontal bars, not much different really) – cphlewis Jul 06 '15 at 20:15

1 Answers1

3

You can get the bars from the plot and then get the height of each bar. You could also use the data values directly, but it's less flexible (eg, if stacked bars are used):

enter image description here

import matplotlib.ticker as ticker
import matplotlib.pyplot as plt

data = [1, 1, 1, 2, 2, 1, 1, 1, 2, 3, 3, 5]

ax = plt.axes()
bars = ax.bar(range(len(data)), data, color='g')

labels = 'Firts label', 'The Second One', 'Labes', 'Foo', 'Bar', 'Last Label'

for label, rect in zip(labels, bars):
    height = rect.get_height()
    ax.text(rect.get_x()+rect.get_width()/2., height+.1, label,
        ha='center', va='bottom', rotation=90)    

plt.show()
tom10
  • 67,082
  • 10
  • 127
  • 137