lassence.net

Manually create a legend on a Matplotlib plot

--- archive: codebook, 2020–2023 topic: Python ---

When you definitely can’t find a way to properly display your legend on a Matplotlib plot, the last hacky solution is to define it completely manually:

import matplotlib.patches as mpatches

leg_control = mpatches.Patch(color='steelblue', fill=None, label='Control')
leg_target = mpatches.Patch(color='darkorange', label='Target')

ax.legend(handles=[leg_control, leg_target])

The code above creates two patches (leg_control and leg_target) with different colors, fill and labels. The last line adds the legend to the plot, with the ax variable that should be defined as the axis of the plot.

Subscribed, thanks. Your address is only used for this newsletter.