0

I'm trying to draw a line with text written on it using the following code:

def angle_line(A, B):
    x = B[0] - A[0]
    y = B[1] - A[1]
    angle = math.atan2(y, x )
    return angle*180/np.pi

fig, ax = plt.subplots()
xy_init = (0,0)
xy_end = (1, 0.5)

#PLOT LINE
ax.plot((xy_init[0], xy_end[0]), (xy_init[1], xy_end[1]), color='black', linewidth=0.5, linestyle='--')


center = (xy_init[0]+xy_end[0])/2, (xy_init[1]+xy_end[1])/2
angle = angle_line(xy_init, xy_end)

#PLOT TEXT
ax.text(*center, 'TEST', horizontalalignment='center', rotation = angle,
        verticalalignment='center',fontdict={'fontsize': 20}, color='red')

Basically, I draw the line using the two points, and then for the text, I calculate the angle and rotate the text accordingly. But, for some reason I cannot comprehend, they are misaligned, as shown in the picture below:

Plot

Do I understand something wrong about the parameters of the matplotlib functions, or is there any problem with the code above?

Bruno Mello
  • 4,448
  • 1
  • 9
  • 39
  • you are doing `center = center = ...` this looks incorrect – Sembei Norimaki Jan 09 '23 at 17:30
  • Thanks, @SembeiNorimaki, I already correct that, but it keeps the same behavior – Bruno Mello Jan 09 '23 at 17:32
  • One thing you might try to debug this issue is to add `aspect='equal'` when you create your figure, or use `set_aspect('equal')` on the axes. [example](https://matplotlib.org/stable/gallery/subplots_axes_and_figures/axis_equal_demo.html) – lmjohns3 Jan 09 '23 at 17:35
  • 4
    You are calculating the angle of the line in "data coordinates", while the rotation of the text is given in "screen coordinates". You can use `ax.set_aspect('equal')` for both to match. – JohanC Jan 09 '23 at 17:35
  • See also [Text Rotation Relative To Line](https://matplotlib.org/stable/gallery/text_labels_and_annotations/text_rotation_relative_to_line.html) from the matplotlib tutorial. It uses `transform_rotates_text=True` (I suppose this is a relatively new option). – JohanC Jan 09 '23 at 17:38

0 Answers0