与底部旋转文本对齐

时间:2015-07-06 19:25:09

标签: matplotlib

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

我有一个每个栏的标签列表。如果我创建一个将条形数据作为参数的函数,如何动态地将标签对齐到条形顶部?

1 个答案:

答案 0 :(得分:3)

您可以从情节中获取bars,然后获得每个条形的高度。您也可以直接使用数据值,但灵活性较差(例如,如果使用堆叠条):

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()