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

时间:2011-11-18 12:04:30

标签: python matplotlib

我在matplotlib中有一个绘图,我的问题是因为当绘图窗口调整​​大小时,x ax将字符串作为值,它们重叠并且无法清晰读取。

类似的事情发生在图例中,如果调整窗口大小,它不会调整大小。

有设置吗?

1 个答案:

答案 0 :(得分:11)

不完全是。 (看看the new matplotlib.pyplot.tight_layout() function有些模糊的东西,但是......)

然而,长x刻度标签的常用技巧就是旋转它们。

例如,如果我们有一些重叠的xticklabels:

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