注意
转到末尾 下载完整示例代码。
数据坐标中的文本旋转角度#
Matplotlib 中的文本对象通常是相对于屏幕坐标系旋转的(即,无论坐标轴如何改变,45 度旋转都会使文本沿介于水平和垂直之间的直线绘制)。然而,有时我们希望文本相对于绘图上的某个对象进行旋转。在这种情况下,正确的角度不是该对象在绘图坐标系中的角度,而是该对象在屏幕坐标系中“看起来”的角度。通过设置参数 transform_rotates_text,可以自动确定此角度,如下例所示。

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Plot diagonal line (45 degrees in data coordinates)
ax.plot(range(0, 8), range(0, 8))
ax.set_xlim([-10, 10])
# Plot text
ax.text(-8, 0, 'text 45° in screen coordinates', fontsize=18,
rotation=45, rotation_mode='anchor')
ax.text(0, 0, 'text 45° in data coordinates', fontsize=18,
rotation=45, rotation_mode='anchor',
transform_rotates_text=True)
plt.show()