How to add a legend in a Matplotlib chart?

In today’s hands on data visualization tutorial we’ll learn how to insert a legend into an existing chart.

Rendering a Matplotlib chart

We’ll use Python and the Matplotlib library to draw a simple line chart. In our example we would like to show the revenue from B2B vs B2C sales of an imaginary company during last year. We’ll use a very simple line plot, but you can use the same method for any Matplotlib chart.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace (1,50,25)
y = x**3
z =  x**2

fig, ax = plt.subplots()
ax.set_title('B2B vs B2C revenue');

Here’s our chart:

As you can note, our chart lacks a meaningful legend. We would like to go ahead and add one.

Insert a legend to a Matplotlib plot

Here’s the code we’ll need:

fig, ax = plt.subplots()
ax.plot(x,y, label = 'B2B sales')
ax.plot(x,z, label ='B2C sales')
ax.set_title('B2B vs B2C revenue');
ax.legend(facecolor = 'gray', title = 'Legend',loc = 'upper left');

Detailed Explanation:

  • We use the parameter label to pass the legend text for each of the plots.
  • We then call the ax.legend method to show the legend on the chart.
  • We use the facecolor parameter to modify the legend background color. We can use a colormap as needed.
  • We use the loc parameter to pass our preferred location for the legend. We can obviously use other locations which follow the same logic: upper right, lower right, lower left etc’.

Don’t show the legend

If we don’t want to show the legend, simple erase the call to the ax.legend method. Note that if your legend interferes with your chart, you can easily place outside the plot area by using the bbox_to_anchor parameter.

Additional learning