Zak
Zak

Reputation: 377

Sort arrays by two criteria

My figure has a very large legend, and to make it easier to find each corresponding line, I want to sort the legend by the y value of the line at the last datapoint.

plots[] contains a list of Line2D objects,

labels[] is the corresponding labels to each Line2D object, generated through labels = [plot._label for plot in plots]

I want to sort each/both arrays by plots._y[-1], the value of y at the last point

Bonus points if I can also sort first by _linestyle (a string) and then by the y value.

I am unsure of how to do this well, I wouldn't think it would require a loop, but it might because I am sorting by 2 criteria, one of which will be tricky to deal with (':' and '-' are the values of linestyle). Is there a function that can help me out here?

edit: it just occurred to me that I can generate labels after I sort, so that uncomplicates things a bit. However, I still have to sort plots by each object's linestyle and y[-1] value.

Upvotes: 1

Views: 108

Answers (1)

Totem
Totem

Reputation: 7349

I believe this may work:

sorted(plots, key = lambda plot :(plot._linestyle, plot._y[-1])) 

Upvotes: 1

Related Questions