Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Approximation of the Perl 'Decorate-Sort-Undecorate' idiom. Demonstrated on the the example of reordering the items in a matplotlib legend.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({'font.size': 14})
# init figure
fig, ax = plt.subplots(1,1, figsize=(10,7))
# generate artificial data
line_a = np.linspace(100, 0, 85)
line_b = np.linspace(80, 0, 65)
line_c = np.linspace(60, 0, 45)
line_d = np.linspace(40, 0, 25)
# plot artificial data
plt.plot(line_c, ls="-.", label="0.45 Alg. A [Version 0.2]")
plt.plot(line_b, ls="--", label="0.65 Alg. B [Version 0.1]")
plt.plot(line_a, ls=":", label="0.85 Alg. A [Version 0.1]")
plt.plot(line_d, label="0.25 Alg. B [Version 0.2]")
# get handles and labels
handles, labels = ax.get_legend_handles_labels()
# create decorated list
# this simply cuts the performance measure from the label string
decorated = [text[5:] for text in labels]
# create a list of indices and sorte the indicies, according to decorated list
sorted_indices = list(range(len(decorated)))
sorted_indices.sort(key=decorated.__getitem__)
# create new lists of labels and handles by mapping the osrted indices to the original two lists
ordered_labels = list(map(labels.__getitem__, sorted_indices))
ordered_handles = list(map(handles.__getitem__, sorted_indices))
# use the ordered legend entries to manually generate the legend
plt.legend(labels=ordered_labels, handles=ordered_handles)
# plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment