备注
前往结尾 下载完整示例代码。
数据坐标中的文本旋转角度#
在 matplotlib 中,文本对象通常相对于屏幕坐标系进行旋转(即,45 度旋转的文本沿着一条介于水平和垂直之间的线,无论轴如何变化)。然而,有时我们希望文本相对于图中的某个对象进行旋转。在这种情况下,正确的角度不是该对象在图坐标系中的角度,而是该对象在屏幕坐标系中显示的角度。这个角度可以通过设置参数 transform_rotates_text 来自动确定,如下例所示。

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
# Plot diagonal line (45 degrees)
h = ax.plot(range(0, 10), range(0, 10))
# set limits so that it no longer looks on screen to be 45 degrees
ax.set_xlim([-10, 20])
# Locations to plot text
l1 = np.array((1, 1))
l2 = np.array((5, 5))
# Rotate angle
angle = 45
# Plot text
th1 = ax.text(*l1, 'text not rotated correctly', fontsize=16,
rotation=angle, rotation_mode='anchor')
th2 = ax.text(*l2, 'text rotated correctly', fontsize=16,
rotation=angle, rotation_mode='anchor',
transform_rotates_text=True)
plt.show()