How to Create a Manual Legend in Matplotlib (With Example)


You can use functions from the matplotlib.lines and matplotlib.patches sub-modules to create a manual legend in a matplotlib plot.

The following example shows how to do so.

Example: Create a Manual Legend in Matplotlib

The following code shows how to create a scatter plot in matplotlib with a default legend:

import matplotlib.pyplot as plt

#define data to plot
x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 3, 5, 8, 12, 18, 27]

#create scatter plot of x vs. y
plt.scatter(x, y, label='Original Data', color='steelblue')

#add legend
plt.legend()

#display plot
plt.show()

To create a manual legend with custom lines and squares, we need to import the matplotlib.lines and matplotlib.patches sub-modules.

The following code shows how to use these sub-modules to create a manual legend:

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

#define data to plot
x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 3, 5, 8, 12, 18, 27]

#create scatter plot of x vs. y
plt.scatter(x, y, label='Original Data', color='steelblue')

#define handles and labels that will get added to legend
handles, labels = plt.gca().get_legend_handles_labels()

#define patches and lines to add to legend
patch1 = mpatches.Patch(color='orange', label='First Manual Patch')
patch2 = mpatches.Patch(color='orange', label='First Manual Patch')   
line1 = Line2D([0], [0], label='First Manual Line', color='purple')
line2 = Line2D([0], [0], label='Second Manual Line', color='red')

#add handles
handles.extend([patch1, line1, line2])

#add legend
plt.legend(handles=handles)

#display plot
plt.show()

Matplotlib manual legend

Notice that this legend includes the label for the original data but also includes labels and shapes for items we added manually.

To change the labels or colors of any of the items, simply modify the values for the label and color arguments in the previous chunk of code.

Note: Refer to this tutorial to learn how to change the position of the legend within the plot.

Additional Resources

The following tutorials explain how to perform other common tasks in Matplotlib:

How to Increase Plot Size in Matplotlib
How to Adjust Title Position in Matplotlib
How to Set Axis Ranges in Matplotlib

Leave a Reply

Your email address will not be published.