Matplotlib:将 x 轴刻度标签向左移动一位 [英] Matplotlib: Move x-axis tick labels one position to left

查看:138
本文介绍了Matplotlib:将 x 轴刻度标签向左移动一位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作条形图,我想将 x 轴刻度标签向左移动一个位置.这是情节的代码:

I am making a bar chart and I want to move the x-axis tick labels one position to left. Here is the code of the plot:

matplotlib.rcParams.update(matplotlib.rcParamsDefault)
plt.style.use(['seaborn-white', 'bmh'])

fig1, ax = plt.subplots()

palette = ['#2a5495', '#07a64c', '#e979ad', '#d88432', '#2a5495',
               '#b7040e', '#82c5db', '#b9c09b', '#cd065d', '#4b117f']

x = np.array(df.index)
y = np.array(df.loc[:, 2015])

width = 1.0
lefts = [x * width for x, _ in enumerate(y)]
ax.bar(left = lefts, height = y, width = width, tick_label = x, color = palette, label = ranked_univs)

ax.axis(ymin = 0, ymax = 200, xmin = -0.5, xmax = 9.5)
ax.tick_params(axis='x', which='major', labelsize=8)
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)

fig1.tight_layout()
plt.show()

这是条形图:

有什么线索吗?

推荐答案

您的标签正确放置,如事实所示,如果将它们旋转90°,它们将与条形完美对齐.

Your labels are correctly positioned, as shown by the fact that if you were to rotate them 90°, they would be perfectly aligned with your bars.

fig1, ax = plt.subplots()

palette = ['#2a5495', '#07a64c', '#e979ad', '#d88432', '#2a5495',
               '#b7040e', '#82c5db', '#b9c09b', '#cd065d', '#4b117f']

labels = ['Long misaligned label {}'.format(i) for i in range(10)]
x = range(10)
y = 100+100*np.random.random((10,))

width = 1.0
lefts = [x * width for x, _ in enumerate(y)]
ax.bar(left = lefts, height = y, width = width, tick_label = labels, color = palette)

ax.axis(ymin = 0, ymax = 200, xmin = -0.5, xmax = 9.5)
ax.tick_params(axis='x', which='major', labelsize=8)
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=90)

fig1.tight_layout()
plt.show()

问题在于标签水平居中,因此当您将它们旋转 45° 时,它们似乎与错误的条对齐.要解决此问题,请将标签向右对齐,然后它们就会回到正确的(视觉)位置.

The problem is that the labels are centered horizontally, so when you rotate them 45°, they appear to be aligned with the wrong bar. To fix this, align the labels to the right, and they'll get back to their correct (visual) position.

plt.setp(ax.xaxis.get_majorticklabels(), ha='right')

另一个(可能更简单)选项是使用辅助函数Figure.autofmt_xdate(),它为您处理所有这些.

Another (maybe simpler) option is to use the helper function Figure.autofmt_xdate(), which handles all of this for you.

这篇关于Matplotlib:将 x 轴刻度标签向左移动一位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆