How to Create and Customize Plot Legends in Pandas?

Creating and customizing plot legends in Pandas is a simple process. You can use the .legend() function to create a legend, customize the legend’s location, font size, and other attributes, and even specify the exact labels and colors to use. Additionally, you can use the .set_title() function to add a title to the legend. Finally, you can use the .set_visible() function to toggle the visibility of the legend. With these tools, you can easily create and customize a plot legend with Pandas.


You can use the following basic syntax to add a legend to a plot in pandas:

plt.legend(['A', 'B', 'C', 'D'], loc='center left', title='Legend Title')

The following example shows how to use this syntax in practice.

Example: Create and Customize Plot Legend in Pandas

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'A':7, 'B':12, 'C':15, 'D':17}, index=['Values'])

We can use the following syntax to create a bar chart to visualize the values in the DataFrame and add a legend with custom labels:

import matplotlib.pyplot as plt

#create bar chart
df.plot(kind='bar')

#add legend to bar chart
plt.legend(['A Label', 'B Label', 'C Label', 'D Label'])

We can also use the loc argument and the title argument to modify the location and the title of the legend:

import matplotlib.pyplot as plt

#create bar chart
df.plot(kind='bar')

#add custom legend to bar chart
plt.legend(['A Label', 'B Label', 'C Label', 'D Label'],
            loc='upper left', title='Labels')

Lastly, we can use the size argument to modify the font size in the legend:

import matplotlib.pyplot as plt

#create bar chart
df.plot(kind='bar')

#add custom legend to bar chart
plt.legend(['A Label', 'B Label', 'C Label', 'D Label'], prop={'size': 20})

Notice that the font size in the legend is much larger now.

x