How to modify chart legends with Python and Matplotlib?

It goes without saying that legends help to clarify our charts and stress the message we want to convey with our analysis. In today’s tutorial we’ll learn how to show and customize plot legends with Python.

Create example data

We’ll start by importing the required Pandas Data Analysis libraries and creating the dataset for our example.

# import Pandas, Numby and Matplotlib.Pyplot
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(10)

# Create example data
periods = 12
month_name = pd.date_range('2020-01-10', periods = periods, freq = 'm').month_name()

Showing the chart

We’ll use Matplotlib in order to quickly display our a stacked bar graph:

fig, ax = plt.subplots(figsize=(10,6))
ax.bar(x=month_name, height = qty, label='Interviews')
ax.bar(x=month_name, height = hired, label='Hired')
ax.tick_params(labelrotation=30)
ax.legend();

Important Note: Make sure to call the plt.legend() method. Otherwise your plot legend won’t be showing up.

Moving the legend outside the chart

In the chart above, the legend is cutting off some of the bars. We would start by placing it outside the plot area using the bbbox_to_anchor parameter.

fig, ax = plt.subplots(figsize=(10,6))
ax.bar(x=month_name, height = qty, label='Interviews')
ax.bar(x=month_name, height = hired, label='Hired')
ax.tick_params(labelrotation=30)
ax.legend(bbox_to_anchor= (1.02, 1));

Here’s the result:

Graph legend titles

If we would like to set a title for the legend, we’ll use the title and title_fontsize parameters as shown below:

ax.legend(title= 'Legend', title_fontsize = 13, bbox_to_anchor= (1.02, 1));

Setting the plot legend size in Python

At this point the legend is visible, but we not too legible, and we can easily resize it to bigger dimensions. We do it by setting the size parameter in the prop dictionary.

ax.legend(title= 'Legend', title_fontsize = 15,  prop = {'size' : 13}, bbox_to_anchor= (1.02, 1));

Modify the plot legend color

We can easily set the background color of our legend as shown below. We purposely change the chart type to horizontal bars.

fig, ax = plt.subplots(figsize=(10,6))
ax.barh(y=month_name, width = qty, label='Interviews')
ax.barh(y=month_name, width = hired, label='Hired')
ax.tick_params(labelrotation=30)

ax.legend(title= 'Legend', title_fontsize = 15, facecolor = 'red', prop = {'size' : 13},  bbox_to_anchor= (1.02, 1));

Additional Learning