如何在matplotlib中旋转xticklabel,以使每个xticklabel之间的间距相等? [英] How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal?

查看:824
本文介绍了如何在matplotlib中旋转xticklabel,以使每个xticklabel之间的间距相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在matplotlib中旋转xticklabel,以使每个xticklabel之间的间距相等?

How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal?

例如使用以下代码:

import matplotlib.pyplot as plt
import numpy as np

# Data + parameters
fontsize = 20
t = np.arange(0.0, 6.0, 1)
xticklabels = ['Full', 'token emb', 'char emb', 'char LSTM', 
               'token LSTM', 'feed forward','ANN']

# Plotting
fig = plt.figure(1)
ax = fig.add_subplot(111)
plt.plot(t, t)
plt.xticks(range(0, len(t) + 1))
ax.tick_params(axis='both', which='major', labelsize=fontsize)
ax.set_xticklabels(xticklabels, rotation = 45)
fig.savefig('test_rotation.png', dpi=300, format='png', bbox_inches='tight')

我获得:

每个xticklabel之间的间距不相等.例如,完全"和令牌嵌入"之间的间隔比前馈"和"ANN"之间的间隔大得多.

The spacing between each xticklabel is unequal. For example, the spacing between 'Full' and 'token emb' is much larger than the spacing between 'feed forward' and 'ANN'.

我在Windows 7 SP1 x64 Ultimate上使用Matplotlib 2.0.0和Python 3.5 64位.

I use Matplotlib 2.0.0 and Python 3.5 64-bit on Windows 7 SP1 x64 Ultimate.

推荐答案

标签位于刻度线的中心.它们的边界框宽度不相等,甚至可能重叠,这使它们看起来间距不均.

The labels are centered at the tickmark position. Their bounding boxes are unequal in width and might even overlap, which makes them look unequally spaced.

由于您始终希望将ticklabels链接到其tickmark,因此更改间距实际上不是一个选择.

Since you'd always want the ticklabels to link to their tickmarks, changing the spacing is not really an option.

不过,您可能希望将它们对齐,例如右上角是它们在刻度线下方的定位参考.

However you might want to align them such the the upper right corner is the reference for their positioning below the tick.

为此使用horizontalalignmentha参数并将其设置为"right":

Use the horizontalalignment or ha argument for that and set it to "right":

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

这将导致以下绘图:

另一种选择是保持刻度标签水平居中,但也可以使其垂直居中.这导致相等的间距,但需要进一步调整它们相对于轴的垂直位置.

An alternative can be to keep the ticklabels horizontally centered, but also center them vertically. This leads to an equal spacing but required to further adjust their vertical position with respect to the axis.

ax.set_xticklabels(xticklabels, rotation = 45, va="center", position=(0,-0.28))

如果像问题中那样手动指定刻度线(例如通过plt.xticks或通过ax.set_xticks)或使用分类图,则可以使用以上内容.
如果改为自动显示标签,则不应使用 set_xticklabels.通常,这将使标签和刻度位置变得不同步,因为set_xticklabels将轴的格式设置为FixedFormatter,而定位器保持自动AutoLocator或任何其他自动定位器.

The above can be used if the ticks are specified manually like in the question (e.g. via plt.xticks or via ax.set_xticks) or if a categorical plot is used.
If instead the labels are shown automatically, one should not use set_xticklabels. This will in general let the labels and tick positions become out of sync, because set_xticklabels sets the formatter of the axes to a FixedFormatter, while the locator stays the automatic AutoLocator, or any other automatic locator.

在这种情况下,请使用plt.setp设置现有标签的旋转和对齐方式

In those cases either use plt.setp to set the rotation and alignment of existing labels,

plt.setp(ax.get_xticklabels(), ha="right", rotation=45)

或在它们上循环以设置各自的属性,

or loop over them to set the respective properties,

for label in ax.get_xticklabels():
    label.set_ha("right")
    label.set_rotation(45)

一个例子是

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

t = np.arange("2018-01-01", "2018-03-01", dtype="datetime64[D]")
x = np.cumsum(np.random.randn(len(t)))

fig, ax = plt.subplots()
ax.plot(t, x)

for label in ax.get_xticklabels():
    label.set_ha("right")
    label.set_rotation(45)

plt.tight_layout()
plt.show()

这篇关于如何在matplotlib中旋转xticklabel,以使每个xticklabel之间的间距相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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