Manually add legend Items Python matplotlib

StackOverflow

I am using matlibplot and I would like to manually add items to the legend that are a color and a label. I am adding data to to the plot to specifying there would lead to a lot of duplicates.

My thought was to do:

    ax2.legend(self.labels,colorList[:len(self.labels)])
    plt.legend()

Where self.labels is the number of items I want legend lables for that takes a subset of the large color list. However this yields nothing when I run it.

Am I missing anything?

Thanks

Answer rating: 115

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

Answer rating: 69

For those wanting to add manual legend items into a single/common legend with automatically generated items:

#Imports
import matplotlib.patches as mpatches

# where some data has already been plotted to ax
handles, labels = ax.get_legend_handles_labels()

# manually define a new patch 
patch = mpatches.Patch(color="grey", label="Manual Label")

# handles is a list, so append manual patch
handles.append(patch) 

# plot the legend
plt.legend(handles=handles, loc="upper center")

Example of common legend with manual and auto-generated items:
example of common legend with manual and auto-generated items

ADDED 2021-05-23

complete example with manual line and patch

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.patches as mpatches

plt.plot([1,2,3,4], [10,20,30,40], label="My Data", color="red")

handles, labels = plt.gca().get_legend_handles_labels()

patch = mpatches.Patch(color="grey", label="manual patch")   
line = Line2D([0], [0], label="manual line", color="k")

handles.extend([patch,line])

plt.legend(handles=handles)
plt.show()

enter image description here





Get Solution for free from DataCamp guru