使用matplotlib将条形图中的xticklabels对齐

时间:2016-12-27 22:53:23

标签: python matplotlib

我正在尝试在matplotlib中生成一个条形图。我的情节更复杂,但主要问题是对齐xlabels。

我现在所拥有的是:

import matplotlib.pyplot as plt
import random
random.seed(0)

counts = [random.randint(10000000000, 20000000000) for i in xrange(15)]
x_labels = ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) # I actually have many subplots, but this is not related to a problem
ax.bar(range(len(counts)), [v / 1000. for v in counts], align='center')
ax.set_title('some title')
ax.set_ylabel('some y label')
ax.set_xticklabels(x_labels, rotation='vertical', ha='center')
ax.set_ylim(bottom=0)
ax.get_figure().tight_layout()
ax.get_figure().subplots_adjust(top=0.97)

plt.show()

产生15个柱:

enter image description here

问题在于我希望我的标签('10','11',...,'24')位于每个条形图(15条,15个标签)的正下方。但由于某种原因,我在左边的某个地方贴上了标签'10',我的标签'11'在第一个标尺下面,标签'20'甚至都看不到。

1 个答案:

答案 0 :(得分:4)

你需要告诉每个人去的位置(你用于酒吧的那个位置):

ax.set_xticks(range(len(counts)))

enter image description here