我想在两个点之间添加一个带有文本的注释,并将文本旋转以与直线对齐。目前的示例无法按预期旋转:
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()
当前输出:
![输入图像描述](https://istack.dev59.com/c9urD.webp)
p1
和p2
的值是什么? - mkrieger1