How to make the multiple blue legends a single one and adjust its position?

Question:

I am trying to draw the following example as a test.
Test

I need to adjust the legend. Instead of multiple (LoS); I need one like the red line Bresenham’s and to adjust its position instead of being in the middle of the figure as shown below.
enter image description here

Python code:

Main

import lineofsights as los
import LineOfSight as bren
import matplotlib.pyplot as plt
import numpy as np

drone_height = 60
risk = [x for x in range(50,60)]
elevation = [[0 for x in range(10)] for y in range(20)]

x1, y1 = 0,0
x2, y2 = 1,9
print("result from lineofsights:")
los.lineOfsight(elevation, risk, drone_height, y1, x1, y2, x2)

print("nn")

print("result from bresenham")
bren.get_line((x1,y1), (x2,y2), elevation, drone_height, risk)


xx = [x for x in range(len(elevation[0]))]
yy = [y for y in range(len(elevation))]

xx,yy = np.meshgrid(xx,yy)

plt.plot(xx,yy,"sb",markersize=17,label="LoS")

a = len(elevation)-1

plt.plot([y1, y2],[a-x1, a-x2], "-r",label="Bresenham's")

plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()
Asked By: SH_IQ

||

Answers:

IIUC easiest is just to fetch the handles and labels from gca (get current axes) and manually truncate them (just get the last two), as well as moving the legend using bbox_to_anchor. So replace plt.legend() with something like this:

handles, labels = plt.gca().get_legend_handles_labels()
plt.legend(handles=handles[-2:], labels=labels[-2:], bbox_to_anchor=(1.35,0.5))

plt.show()

enter image description here

Answered By: Josh Friedlander
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.