How to manually create a legend

Have you checked the Legend Guide?

For practicality, I quote the example from the guide.

Not all handles can be turned into legend entries automatically, so it
is often necessary to create an artist which can. Legend handles don’t
have to exists on the Figure or Axes in order to be used.

Suppose we wanted to create a legend which has an entry for some data
which is represented by a red color:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color="red", label="The red data")
plt.legend(handles=[red_patch])

plt.show()

enter image description here

Edit

To add two patches you can do this:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color="red", label="The red data")
blue_patch = mpatches.Patch(color="blue", label="The blue data")

plt.legend(handles=[red_patch, blue_patch])

enter image description here

Leave a Comment