Matplotlib has the text
and annotate
functions to plot text into a graph. In your case, text
will suffice. In the original answer (see below), I have tried to keep your structure as much as possible but since the distances have to be calculated for the plot anyhow, I have integrated this into the plot loop to avoid code repetition. But the original simple approach looked weird for slopes other than ascending. So, here is an improved version while keeping your general structure:
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
my_list = [[1, 2], [10, 20], [30, 80], [70, 50], [110, 120], [180, 190], [130, 20], [180, 20], [10, 120], [10, 150]]
def DistanceBwPoints(ln1):
x1 , y1 = ln1[0][0] , ln1[0][1]
x2 , y2 = ln1[1][0] , ln1[1][1]
dis = sqrt ((x2 - x1)**2 + (y2 - y1)**2 )
return dis
def visualization2(a,b):
x1 = []
y1 = []
for pt in a:
x1 += [pt[0]]
y1 += [pt[1]]
plt.plot(x1,y1, 'yo')
m1 = range(len(x1))
for i in np.arange(0,len(m1)-1,2):
#plot line
plt.plot(x1[i:i+2],y1[i:i+2], color=b)
#calculate distance
curr_dist = round(DistanceBwPoints([my_list[i], my_list[i+1]]),2)
print(f"Line number {i//2+1} with distance", curr_dist)
#determine slope direction of line to set text anchors correctly
ln_slope = 1 + int(np.sign(np.diff(x1[i:i+2]) * np.diff(y1[i:i+2])))
text_anchor_ha = ["left", "center", "right"][ln_slope]
text_anchor_va = "bottom"
#special case vertical line
if not np.diff(x1[i:i+2]):
text_anchor_ha, text_anchor_va = "right", "center"
#annotate line
plt.text(x=np.mean(x1[i:i+2]), y=np.mean(y1[i:i+2]), s=curr_dist, ha=text_anchor_ha, va=text_anchor_va)
visualization2(my_list,'red')
plt.axis('equal')
plt.show()
Sample output:

And one more thing - I have changed from math import *
. Please read here why import *
is a bad idea.
Original answer
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
def DistanceBwPoints(ln1):
x1 , y1 = ln1[0][0] , ln1[0][1]
x2 , y2 = ln1[1][0] , ln1[1][1]
dis = sqrt ((x2 - x1)**2 + (y2 - y1)**2 )
return dis
def visualization2(a,b):
x1 = []
y1 = []
for pt in a:
x1 += [pt[0]]
y1 += [pt[1]]
plt.plot(x1,y1, 'yo')
m1 = range(len(x1))
for i in np.arange(0,len(m1)-1,2):
plt.plot(x1[i:i+2],y1[i:i+2], color=b)
curr_dist = round(DistanceBwPoints([my_list[i], my_list[i+1]]),2)
print(i, curr_dist)
plt.text(x=np.mean(x1[i:i+2]), y=np.mean(y1[i:i+2]), s=curr_dist, ha="right", va="bottom")
my_list = [[416689.15984457487, 5961369.921824793], [416463.47437214176, 5961262.376170568], [416784.93559347134, 5961169.622417776], [416662.37786889425, 5961110.342221191], [416882.24253254064, 5960968.447021521], [416861.28136564675, 5960958.308271814]]
visualization2(my_list,'red')
plt.axis('equal')
plt.show()
Sample output:
