gpt4 book ai didi

python - 计算 Matplotlib 文本旋转

转载 作者:行者123 更新时间:2023-12-01 09:18:17 25 4
gpt4 key购买 nike

我试图弄清楚如何在 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 笔记本中的选项。]

enter image description here

最佳答案

正如评论中所建议的,您可能需要包含抽象表示(轴大小)和实际图形(图形大小)之间的比例关系。当曲线的角度取决于轴的刻度时,文本的旋转角度是绝对测量

# 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()

enter image description here

关于python - 计算 Matplotlib 文本旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51028431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com