如何在matplotlib中注释带有沿着线旋转的文本的线

3

我想在两个点之间添加一个带有文本的注释,并将文本旋转以与直线对齐。目前的示例无法按预期旋转:

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

当前输出: 输入图像描述

p1p2的值是什么? - mkrieger1
1个回答

5

添加两个text参数以使文本旋转与线匹配:

  1. transform_rotates_text=True 相对于图形比例尺旋转文本
  2. rotation_mode='anchor' 将旋转固定在相对于vaha的锚点上
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)


1
谢谢,它运行良好。有任何参数可以将文本从线条稍微移开一点吗?如果为文本添加背景颜色,当前文本将与线条重叠。 - lucky1928
@lucky1928 我不知道有没有这样的方法,特别是当使用背景颜色时。如果没有背景,一个解决方法是在文本中添加一个换行符,并调整 linespacing 参数:ax.text(midx, midy, f'{text}\n', ha='center', va='bottom', rotation=rotn, rotation_mode='anchor', transform_rotates_text=True, linespacing=0.5) - tdy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接