【发布时间】:2018-12-04 07:43:26
【问题描述】:
我正在尝试弄清楚如何在 matplotlib 中旋转文本以与绘图中的曲线对齐,但我还没有弄清楚哪些转换可以为旋转文本提供正确的坐标系以匹配数据坐标中的特定斜率。这是绘制一条线并尝试沿其对齐一些文本的最小示例:
# Make some really non-square figure
plt.figure(figsize=(2,5))
# Draw some line between two points
pB=np.array((0,0))
pA=np.array((1,2))
pC=(pA+pB)/2
plt.plot(*zip(pA,pB))
# All the transforms at our disposal
tD=plt.gca().transData
tA=plt.gca().transAxes
tF=plt.gcf().transFigure
# Transform the endpoints of the line two some coordinate system
pA,pB=[
##### What goes here???
p # <- trivial no transform
#tD.transform(p)
#tA.inverted().transform(tD.transform(p))
#tF.inverted().transform(tD.transform(p))
for p in (pA,pB)]
# Then calculate the angle of the line
rise,run=pA-pB
rot=(180/np.pi)*np.arctan(rise/run)
# Draw some text at that angle
plt.text(pC[0],pC[1],'hi there',rotation=rot,
horizontalalignment='center',verticalalignment='bottom');
无论我怎么尝试,文本仍然是错误的:
[此图像用于上述无转换情况,由 Jupyter 笔记本中的 %matplotlib inline 选项呈现。]
【问题讨论】:
-
如果你仔细想想,当曲线的角度取决于轴的刻度时,文本的旋转角度是一个绝对量度。为了快速观察,更改绘图窗口的大小。所以,我猜旋转角度的演算应该以某种方式涉及到关于轴的信息。
-
@UncleBenBen 我同意这种直觉,并且在这个问题中,我专门选择了一个非常窄的数字尺寸以使错误方向明显。尽管如此,尝试的所有三种转换(在上面代码中的 cmets 中)都考虑了该信息,但仍然无法正确捕获角度,所以我不知所措。
标签: python matplotlib plot transform