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

标签 python matplotlib plot label

<分区>

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

例如这段代码:

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

我得到:

enter image description here

每个xticklabel 之间的间距不相等。例如,“Full”和“token emb”之间的间距比“feed forward”和“ANN”之间的间距大得多。

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

最佳答案

标签在刻度线位置居中。它们的边界框宽度不等,甚至可能重叠,这使得它们看起来间隔不等。

enter image description here

由于您总是希望刻度标签链接到它们的刻度标记,因此更改间距并不是一个真正的选择。

但是您可能希望将它们对齐,例如右上角是它们在刻度线下方定位的引用。

为此使用horizo​​ntalalignmentha 参数并将其设置为"right":

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

这导致了以下情节:

enter image description here

另一种方法是让刻度标签水平居中,但也垂直居中。这导致间距相等,但需要进一步调整它们相对于轴的垂直位置。

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

enter image description here


enter image description here

如果像问题中一样手动指定刻度(例如,通过 plt.xticks 或通过 ax.set_xticks),或者如果分类图是用过。
相反,如果标签自动显示,则不应使用 set_xticklabels。这通常会让标签和刻度位置变得不同步,因为 set_xticklabels 将轴的格式化程序设置为 FixedFormatter,而定位器保持自动 AutoLocator,或任何其他自动定位器。

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

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

或遍历它们以设置各自的属性,

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

关于python - 如何在 matplotlib 中旋转 xticklabels 以使每个 xticklabel 之间的间距相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43152502/

相关文章:

python - PyQtGraph:通过绘制数据切片发出循环

python - 为什么使用 FuncAnimation 绘图时点不移动?

python - 获取 matplotlib 颜色循环状态

python - 无法为 matplotlib 子图绘制图例/轴

r - 在 R 中创建桑基图;使绘图输出可解释

Python 全局图像目录

python - 修改字典中的值

python - 在 yt-Project 图中添加子图

r - 如何在R中移动绘图

python - Matplotlib 饼图 explode 而不是圆形