Следующая функция ищет дескрипторы дескрипторов и меток и сортирует или частично сортирует их в соответствии с заданным списком (order
):
def reorderLegend(ax=None,order=None,unique=False):
"""
Returns tuple of handles, labels for axis ax, after reordering them to conform to the label order `order`, and if unique is True, after removing entries with duplicate labels.
"""
if ax is None: ax=plt.gca()
handles, labels = ax.get_legend_handles_labels()
# sort both labels and handles by labels
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
if order is not None: # Sort according to a given list (not necessarily complete)
keys=dict(zip(order,range(len(order))))
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t,keys=keys: keys.get(t[0],np.inf)))
if unique: # Keep only the first of each handle
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))]
Функция в обновленной форме находится в cpblUtilities.mathgraph
в http://github.com/cpbl
Цитаты: Кевин (эта страница) и Маркус Ярдерот ( Как удалить дубликаты из списка в сохраняя порядок? ).