python - 计算 Matplotlib 文本旋转
问题描述
我试图弄清楚如何在 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()
推荐阅读
- mariadb - MariaDB如何在现有数据库中进行字符集转换?
- node.js - 使用 ngrx 部分同步客户端状态
- c# - Windows 服务可以使用由另一个 Windows 服务托管的 WCF 服务吗?
- java - 无法实例化类型(类)?
- angular - 如何避免 Angular 中重复的 ViewChildren?
- perl - perl 中的 getopts 问题
- javascript - javascript中ceil函数的问题
- list - 对列表飞镖内的整数列表求和
- gradle - 无法解析符号junit
- botframework - 无法设置 OAuthconnection 设置