Matplotlib:将x轴刻度标签向左移动一个位置

时间:2017-04-20 13:00:54

标签: python matplotlib

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

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()

以下是条形图:

enter image description here

有任何线索吗?

2 个答案:

答案 0 :(得分:6)

您的标签位置正确,如果您将它们旋转90°,它们将与您的酒吧完美对齐。

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()

enter image description here

问题是标签水平居中,因此当您将它们旋转45°时,它们似乎与错误的条形对齐。要解决此问题,请将标签对齐,然后它们将返回正确的(可视)位置。

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

enter image description here

另一个(可能更简单)选项是使用helper function Figure.autofmt_xdate(),它会为您处理所有这些。

答案 1 :(得分:2)

请参阅此问题:How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal?

解决方案是将标签对齐到右侧:

ax.set_xticklabels(xticklabels, rotation = 45, ha="right")