相对于线条的文本旋转

Matplotlib中的文本对象通常相对于屏幕坐标系旋转(即45度旋转沿水平和垂直线绘制文本,无论轴如何更改)。然而,有时人们希望相对于绘图上的某些内容旋转文本。在这种情况下,正确的角度不是绘图坐标系中该对象的角度,而是该对象在屏幕坐标系中显示的角度。通过将绘图角度转换为屏幕坐标系,可以找到这个角度,如下面的示例所示。

text rotation relative to line
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
trans_angle = ax.transData.transform_angles([45], l2.reshape((1, 2)))[0]

# 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=trans_angle, rotation_mode='anchor')

plt.show()

关键词:matplotlib代码示例,codex,python plot,pyplot Gallery generated by Sphinx-Gallery