如何在 matplotlib 中用沿线旋转的文本注释线
How to annotate line with text rotated along the line in matplotlib
我想在两点之间添加一个注释,文本在中间,然后旋转文本以与直线对齐。
当前示例未按预期旋转:
import matplotlib.pyplot as plt
import numpy as np
def ann_distance(ax,xyfrom,xyto,text=None):
midx = (xyto[0]+xyfrom[0])/2
midy = (xyto[1]+xyfrom[1])/2
if text is None:
text = str(np.sqrt( (xyfrom[0]-xyto[0])**2 + (xyfrom[1]-xyto[1])**2 ))
ax.annotate("",xyfrom,xyto,arrowprops=dict(arrowstyle='<->'))
p1 = ax.transData.transform_point((xyfrom[0], xyfrom[1]))
p2 = ax.transData.transform_point((xyto[0], xyto[1]))
rotn = np.degrees(np.arctan2(p2[1]-p1[1], p2[0]-p1[0]))
ax.text(midx,midy,text,ha='center', va='bottom',rotation=rotn,fontsize=16)
return
x = np.linspace(0,2*np.pi,100)
width = 800
height = 600
fig, ax = plt.subplots()
ax.plot(x,np.sin(x))
ann_distance(plt.gca(),[np.pi/2,1],[2*np.pi,0],'$sample$')
plt.show()
当前输出:
添加两个 text
参数使文本旋转与行匹配:
transform_rotates_text=True
相对于图形比例旋转文本
rotation_mode='anchor'
anchors the rotation relative to va
and ha
dx = xyto[0] - xyfrom[0]
dy = xyto[1] - xyfrom[1]
rotn = np.degrees(np.arctan2(dy, dx)) # not the transformed p2 and p1
ax.text(midx, midy, text, ha='center', va='bottom', fontsize=16,
rotation=rotn, rotation_mode='anchor', transform_rotates_text=True)
我想在两点之间添加一个注释,文本在中间,然后旋转文本以与直线对齐。 当前示例未按预期旋转:
import matplotlib.pyplot as plt
import numpy as np
def ann_distance(ax,xyfrom,xyto,text=None):
midx = (xyto[0]+xyfrom[0])/2
midy = (xyto[1]+xyfrom[1])/2
if text is None:
text = str(np.sqrt( (xyfrom[0]-xyto[0])**2 + (xyfrom[1]-xyto[1])**2 ))
ax.annotate("",xyfrom,xyto,arrowprops=dict(arrowstyle='<->'))
p1 = ax.transData.transform_point((xyfrom[0], xyfrom[1]))
p2 = ax.transData.transform_point((xyto[0], xyto[1]))
rotn = np.degrees(np.arctan2(p2[1]-p1[1], p2[0]-p1[0]))
ax.text(midx,midy,text,ha='center', va='bottom',rotation=rotn,fontsize=16)
return
x = np.linspace(0,2*np.pi,100)
width = 800
height = 600
fig, ax = plt.subplots()
ax.plot(x,np.sin(x))
ann_distance(plt.gca(),[np.pi/2,1],[2*np.pi,0],'$sample$')
plt.show()
当前输出:
添加两个 text
参数使文本旋转与行匹配:
transform_rotates_text=True
相对于图形比例旋转文本rotation_mode='anchor'
anchors the rotation relative tova
andha
dx = xyto[0] - xyfrom[0]
dy = xyto[1] - xyfrom[1]
rotn = np.degrees(np.arctan2(dy, dx)) # not the transformed p2 and p1
ax.text(midx, midy, text, ha='center', va='bottom', fontsize=16,
rotation=rotn, rotation_mode='anchor', transform_rotates_text=True)