Sorry for the typos ..(if any)
Here is my answer... It is a slight tweak of @paddyg's answer, and yes, the resizing the chart with the mouse upon display will cause aligment issues.
You will have to tweak the offset and the chart dimensions
Outputs:
Image 1 has window size(10,5),offset(0,1)
Image 2 has window size(10,5),offset(-4,0)
import matplotlib.pyplot as plt
import math
# I've used 3 plots here:
x_range = [i for i in range(0,101)]
y1_range = [i/1 for i in range(0,101)]
y2_range = [i/2 for i in range(0,101)]
y3_range = [i/3 for i in range(0,101)]
# Size of the ouput figure
x_fig = 10
y_fig = 5
plt.figure(figsize=(x_fig, y_fig))
# The height offset form the midpoint of the line segments
offset = [0,1]
def angle(rng,point,x_fig,y_fig):
'''
This will return the alignment angle
'''
# print("rng = ", rng)
x_scale = x_fig /(rng[1] - rng[0])
y_scale = y_fig /(rng[3] - rng[2])
assert len(point) == 2, 'point is not properly defined'
x = point[0]
y = point[1]
rot = ((math.atan2( y*y_scale , x*x_scale ))*180)/math.pi
print(rot,point)
return rot
def center_point(start,end,height_offset):
'''
This will return the location of text placement
'''
x_mid = (end[0]-start[0])/2
y_mid = (end[1]-start[1])/2
return[x_mid+height_offset[0],y_mid+height_offset[1]]
# Plotting graphs...
plt.plot(x_range,y1_range,color='pink',label = 'y1 - graph')
plt.plot(x_range,y2_range,color='blue',label = 'y2 - graph')
plt.plot(x_range,y3_range,color='red',label = 'y3 - graph')
rng = plt.axis() # This gives the axes range
rot_y1 = angle(rng,[x_range[-1],y1_range[-1]],x_fig,y_fig)
pos_y1 = center_point([x_range[0],y1_range[0]],[x_range[-1],y1_range[-1]],offset)
rot_y2 = angle(rng,[x_range[-1],y2_range[-1]],x_fig,y_fig)
pos_y2 = center_point([x_range[0],y2_range[0]],[x_range[-1],y2_range[-1]],offset)
rot_y3 = angle(rng,[x_range[-1],y3_range[-1]],x_fig,y_fig)
pos_y3 = center_point([x_range[0],y3_range[0]],[x_range[-1],y3_range[-1]],offset)
# Annotating them...(Of course this can be done in a loop as @paddyg's answer suggets.)
plt.annotate('Y1 is here', xy =(0, 0),
xytext =(pos_y1[0], pos_y1[1]),
rotation=rot_y1)
plt.annotate('Y2 is here', xy =(0, 0),
xytext =(pos_y2[0], pos_y2[1]),
rotation=rot_y2)
plt.annotate('Y3 is here', xy =(0, 0),
xytext =(pos_y3[0], pos_y3[1]),
rotation=rot_y3)
plt.legend()
plt.xlabel('X - Values')
plt.ylabel('Y - Values')
plt.title('Align the names correctly!')
plt.savefig('demo.png', transparent=True) # Do you want to save a backgroundless .png of the graph?
plt.show()