如何在matplotlib中自动调整文本大小?

8 投票
1 回答
3992 浏览
提问于 2025-04-17 06:35

我在使用matplotlib画图,遇到一个问题:因为x轴的值是字符串,当我调整图窗大小时,这些字符串会重叠在一起,变得不太清楚。

类似的情况也发生在图例上,图例在窗口调整大小时不会跟着一起调整。

有没有什么设置可以解决这个问题呢?

1 个回答

11

其实不是完全一样的。(不过你可以看看新的 matplotlib.pyplot.tight_layout() 函数,它有点类似……)

不过,处理长的x轴标签的常用方法就是把它们旋转一下。

比如说,如果我们有一些重叠的x轴标签:

import matplotlib.pyplot as plt

plt.plot(range(10))
labels = [15 * repr(i) for i in range(10)]
plt.xticks(range(10), labels)
plt.show()

enter image description here

我们可以把它们旋转,这样就更容易阅读了:(关键是 rotation=30。调用 plt.tight_layout() 只是调整了图表底部的边距,以防标签超出底边。)

import matplotlib.pyplot as plt

plt.plot(range(10))
labels = [10 * repr(i) for i in range(10)]
plt.xticks(range(10), labels, rotation=30)
plt.tight_layout()
plt.show()

enter image description here

默认情况下,刻度标签是居中在刻度上的。对于旋转的标签,通常让标签的左边或右边与刻度对齐会更合理。

比如说,像这样(右侧,正旋转):

import matplotlib.pyplot as plt

plt.plot(range(10))
labels = [10 * repr(i) for i in range(10)]
plt.xticks(range(10), labels, rotation=30, ha='right')
plt.tight_layout()
plt.show()

enter image description here

或者这样(左侧,负旋转):

import matplotlib.pyplot as plt

plt.plot(range(10))
labels = [10 * repr(i) for i in range(10)]
plt.xticks(range(10), labels, rotation=-30, ha='left')
plt.tight_layout()
plt.show()

enter image description here

撰写回答