小编典典

matplotlib条形图,在条形中间设置xticklabel的通用方法

python

以下代码生成一个带有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)

阅读 1036

收藏
2021-01-20

共1个答案

小编典典

因此,问题在于您只能致电ax.set_xticklabels。这样可以固定标签,但是刻度位置仍由来处理,AutoLocator在更改轴限制时会添加/删除刻度。

因此,您还需要修复刻度位置:

ax.set_xticks(x)
ax.set_xticklabels(xl)

通过调用set_xticksAutoLocator替换为引擎盖下的FixedLocator

然后,您可以将条居中以使其看起来更好(可选):

ax.bar(x, y, 0.5, align='center')
2021-01-20