我试图弄清楚如何在 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');
无论我如何尝试,文本仍然是错误的:
[此图像适用于上面的无变换情况,由%matplotlib inline
Jupyter 笔记本中的选项。]
正如评论中所建议的,您可能希望包括抽象表示之间的比例关系(轴尺寸)和实际数字(图形尺寸)。当曲线的角度取决于轴的刻度时,文本的旋转角度是绝对测量值
# define the figure size
fig_x, fig_y = 4, 8
plt.figure(figsize=(fig_x, fig_y))
# 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))
# Calculate the angle of the line
dx, dy = pA-pB
# --- retrieve the 'abstract' size
x_min, x_max = plt.xlim()
y_min, y_max = plt.ylim()
# --- apply the proportional conversion
Dx = dx * fig_x / (x_max - x_min)
Dy = dy * fig_y / (y_max - y_min)
# --- convert gaps into an angle
angle = (180/np.pi)*np.arctan( Dy / Dx)
# Draw text at that angle
plt.text(pC[0], pC[1], 'it worked', rotation=angle,
horizontalalignment='center', verticalalignment='bottom')
plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)