Skip to content

Instantly share code, notes, and snippets.

@frietz58
Created Dec 10, 2019
Embed
What would you like to do?
Update version of the example plot, implicitly applying the 'Decorate-Sort-Undecorate' idiom.
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()
# order both lists
ordered_labels, ordered_handles = zip(*sorted(zip(labels, handles)))
# use the ordered legend entries to manually generate the legend
plt.legend(labels=ordered_labels, handles=ordered_handles)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment