以下代码生成一个条形图,其中xticklabels以每个条形为中心。但是,缩放x轴,更改条数或更改条宽会改变标签的位置。是否存在处理该行为的通用方法?
# This code is a hackish way of setting the proper position by trial
# and error.
import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
# adding 0.75 did the trick but only if I add a blank position to `xl`
x = np.arange(0,len(y)) + 0.75
xl = ['', 'apple', 'orange', 'pear', 'mango', 'peach']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5)
ax.set_xticklabels(xl)
# I cannot change the scaling without changing the position of the tick labels
ax.set_xlim(0,5.5)
建议的和有效的解决方案:
import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
x = np.arange(len(y))
xl = ['apple', 'orange', 'pear', 'mango', 'peach']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5, align='center')
ax.set_xticks(x)
ax.set_xticklabels(xl)
答案 0 :(得分:6)
所以问题是你只能打电话给ax.set_xticklabels
。这会修复标签,但是刻度位置仍然由AutoLocator
处理,这将在更改轴限制时添加/删除刻度。
所以你还需要修正刻度位置:
ax.set_xticks(x)
ax.set_xticklabels(xl)
通过致电set_xticks
,AutoLocator
会被FixedLocator
替换。
然后你可以将条形图居中以使其看起来更好(可选):
ax.bar(x, y, 0.5, align='center')