此代码
import numpy as np
vals = []
for i in range(500):
vals.append(random.randint(-6,6))
edges = np.arange(-6,7,1)
fig, ax = subplots(figsize=(8,5))
ax.hist(vals, bins=edges, rwidth=0.90)
ax.set_xticks(edges)
my_xlabels = [ str(i) for i in edges[:-1] ]
ax.set_xticklabels(my_xlabels)
生成此直方图:
但我需要x轴标签位于条形图的中间,如下所示:
我试图关注https://matplotlib.org/gallery/ticks_and_spines/centered_ticklabels.html#sphx-glr-gallery-ticks-and-spines-centered-ticklabels-py但是这个例子因日期,定位器和格式化程序而变得复杂,我无法弄清楚,也不想要。
寻找简单,理想的1线解决方案。我试过这些,但都没有用:
ax.set_xticklabels(my_xlabels, horizontalalignment='center')
ax.set_xticklabels(my_xlabels, fontdict={'horizontalalignment':'center'})
ax.xaxis.set_ticklabels(my_xlabels, horizontalalignment='center')
xticks(my_xlabels, horizontalalignment='center') #ERROR
for tick in ax.xaxis.get_majorticklabels():
tick.set_horizontalalignment("center")
ax.get_xaxis().majorTicks[1].label1.set_horizontalalignment('center')
ax.get_xaxis().majorTicks[2].label1.set_horizontalalignment('center')