labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
if order is not None:
    keys = dict(zip(order, list(range(len(order)))))
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t, keys=keys:
    keys.get(t[0], np.inf)))
if unique:
    labels, handles = zip(*unique_everseen(zip(labels, handles), key=labels))
ax.legend(handles, labels)
return handles, labels

def unique_everseen(seq, key=None):
    seen = set()
seen_add = seen.add
return [x for x, k in zip(seq, key) if not (k in seen or seen_add(k))]
Как определяется порядок элементов в легенде matplotlib?