Matplotlib: display legend keys for lines as patches by default

Viewed 32

For background, see the legend guide.

I want to display legend keys for Line2D objects as Patches (with the same color and label), by default. What is the cleanest way to do this? I tried using update_default_handler_map with a handler_map but keep getting errors.

1 Answers

Making this appear by default probably wouldn't work, as there are too many differences between lines and patches. Lines can have a line width, markes, line styles, ... . Patches can have an outline, hatching, ....

For a simple situation with just a colored, you might use rectangles:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.random.randn(100).cumsum(), color='tomato', label='red line')
ax.plot(np.random.randn(100).cumsum(), color='cornflowerblue', alpha=0.6, label='blue line')

handles, labels = ax.get_legend_handles_labels()
new_handles = [h if type(h) != matplotlib.lines.Line2D
               else plt.Rectangle((0, 0), 0, 0, lw=0, color=h.get_color(), alpha=h.get_alpha()) for h in handles]

ax.legend(new_handles, labels)
plt.show()

showing lines as patches in legend

Related