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

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

问题描述

如何在 matplotlib 中旋转 xticklabels 以使每个 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之间的间距不等.例如,Full"和token emb"之间的间距远大于feed forward"和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.

因为您总是希望刻度标签链接到它们的刻度线,所以改变间距并不是一个真正的选择.

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.

使用 horizo​​ntalalignmentha 参数并将其设置为 "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 中旋转 xticklabels 以使每个 xticklabel 之间的间距相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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