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

发布于 2021-01-29 15:05:20

以下代码生成一个带有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
被浏览
97
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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

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

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

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

    ax.bar(x, y, 0.5, align='center')
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看