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

Mor*_*itz 3 python matplotlib

以下代码生成一个条形图,其中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)
Run Code Online (Sandbox Code Playgroud)

建议和工作的解决方案:

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)
Run Code Online (Sandbox Code Playgroud)

hit*_*tzg 6

所以问题是你只能打电话ax.set_xticklabels.这会修复标签,但是仍然会处理刻度位置AutoLocator,这会在更改轴限制时添加/删除刻度.

所以你还需要修正刻度位置:

ax.set_xticks(x)
ax.set_xticklabels(xl)
Run Code Online (Sandbox Code Playgroud)

通过呼叫set_xticksAutoLocator引擎盖下更换FixedLocator.

然后你可以使条形中心,使它看起来更好(可选):

ax.bar(x, y, 0.5, align='center')
Run Code Online (Sandbox Code Playgroud)