Home > Software engineering >  How to make the multiple blue legends only a single one and adjusting its position?
How to make the multiple blue legends only a single one and adjusting its position?

Time:10-02

Dears, I am trying as in the figure below to draw the following example as a test

Test

What I need here is to adjust the legend instead of multiple (LoS); I only need one like the red line Bresenham's and I need to adjust its position instead of being in the middle of the figure as shown below.

enter image description here Any assistance please?

The python code below:

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("\n\n")

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

CodePudding user response:

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

  • Related