gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:02 25 4
gpt4 key购买 nike

以下代码生成一个条形图,其中 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)

最佳答案

所以问题是你只调用了ax.set_xticklabels。这修复了标签,但刻度位置仍由 AutoLocator 处理,这将在更改轴限制时添加/删除刻度。

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

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

通过调用 set_xticksAutoLocator 被替换为 FixedLocator .

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

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

关于python - matplotlib barplot,在条形中间设置 xticklabels 的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31067389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com