How to Add Plot Legends in Pandas?

  • Post author:
  • Post category:Pandas
  • Post last modified:January 17, 2024
  • Reading time:19 mins read

plt.legend() is used to change the location of the legend of the plot in Pandas. A legend is nothing but an area of the plot. Plot legends provide clear visualization by telling the functionality of plot elements. matplotlib library provides a legend() function, using this we can modify, customize the legends and change the place of the legend for any type of plot.

This function creates a legend automatically for any labeled plot elements. In this article, I will explain the plt.legend() function and using this syntax and parameters how we can add a legend to bar plot with several examples.

1. Quick Examples of How to Add Plot Legends in Pandas?

If you are in a hurry, below are some quick examples of how to add plot legends in pandas.


# Quick examples of add Plot legends in pandas

# Example 1: Add legend to bar plot
df = pd.DataFrame({"USA":316.3, "Brazil":321.3,"Germany":117.2, "India":38.25, "Uk":302.2}, 
                  index = ["Death Rate"])print(df)
# Create bar plot
df.plot.bar()
plt.title("Death Rate of Covid-19", color = 'red')
plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"])

# Example 2: Change the legend location using loc 
# Set the title to legend
 plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"], loc='lower left', title='Country')

# Example 3: Customize the legend size
plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"], prop={'size': 15})

# Example 4: Customize the legend using frameon
plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"],loc='upper left', frameon=False)

# Example 5: Customize the legend edgecolor and shadow
plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"],loc='upper left', edgecolor = 'red', shadow = True)

# Example 6: Add legend outside of the plot 
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))

2. Syntax of legend() function

Following is the syntax of legend() function.


# Syntax of legend()
plt.legend([], loc='best', title='Legend Title')

2.1 Parameters

The Following are parameters of the legend() function.

  • Loc : Is used to specify the location of the legend. Default value is loc=”best” (upper right). The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure
  • Prop :(Default = None) Font size of legend.
  • labelcolor : (Default = None)The color of the text in the legend.
  • shadow: Is used to draw a shadow behind the legend
  • markerscale: The relative size of legend markers compared with the originally drawn ones.
  • numpoints: [None or int] The number of marker points in the legend when creating a legend entry for a Line2D (line). The Default is None.
  • facecolor: The legend’s background color.
  • frameon :(Default = True) Is used to draw a legend on frame.
  • edgecolor: (Default = None) The legend’s background patch edge color.
  • bbox_to_anchor : Specifies the coordinates of the legend.
  • ncol : (Default = 1) Represents the number of columns that the legend has.

3. Create Plot Bar

We can create a bar graph by calling a plot.bar() on the pandas DataFrame, so let’s create Pandas DataFrame. Here I have created a single row DataFrame with the sample data of the worldwide death rate of covid-19 in the pandemic.


# Create DataFrame
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"USA":316.3, "Brazil":321.3,"Germany":117.2, "India":38.25, "Uk":302.2}, 
                  index = ["Death Rate"])
print(df)
# Create bar plot
df.plot.bar()
plt.title("Death Rate of Covid-19", color = 'red')

# Output:
#              USA  Brazil  Germany  India     Uk
# Death Rate  316.3   321.3    117.2  38.25  302.2

Yields below output.

Pandas plot legend
Pandas DataFrame

As you can see from the above image, by default labels have been added to the bar plot. If we want to create new labels we can go with the legend() function, provides Matplotlib is a data visualization library.

4. Add Legend to Bar plot

Using the legend() function we can add a legend to any plot. Here, I will apply legend on the above plot bar. By default, the legend will add at the ‘upper right'(which is the default location of legend) of the bar plot. If we want to change the location of the legend we can go with 'loc' parameter 'best'(‘upper right’) is the default location.


# Add legend to bar chart
plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"])

Yields below output.

Pandas plot bar with legend labels

5. Customize the Legend in a bar plot

plt.legend() function provides various parameters for changing location and customizing the legends of Matplotlib plot with Pandas. In this article, I will use some of those parameters to customize the legends of plots.

5.1 Use Loc and Title Params

use the loc param and the title param to change the location and set title of the legend. Let’s pass loc and title with specified values,


# Change the legend location using loc 
# Set the title to legend
 plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"], loc='lower left', title='Country')
pandas plot legend
Pandas plot bar with legend labels

5.2 Use Prop Param Customize the Size

Use the prop parameter to update the font size in the legend. Let’s set size : 15 as prop and pass into legend() function. It will change the font size on the legend.


# Customize the legend size
plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"], prop={'size': 15})

Yields below output.

pandas plot legend
Pandas plot bar with customized legend labels

5.3 Customize the Legend using frameon, edgecolor, &shadow

Using the frameon param we can invisible the frame around the legend, by default it is True. If we don’t want the frame around the legend we can set it with False, it can invisible the frame around the legend.


# Customize the legend using frameon
plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"],loc='upper left', frameon=False)

Yields below output.

Pandas plot bar with customized legend labels

We can customize the edge color using edgecolor param and also create shadow of legend using shadow param. Let’s see how they can customize the legend.


# Customize the legend edgecolor and shadow
plt.legend(["USA", "BRAZIL", "GERMANY", "INDIA", "UK"],loc='upper left', edgecolor = 'red', shadow = True)

Yields below output.

pandas plot legend
Add legend at out side of the Pandas plot bar

6. Add Legend Outside of the Plot in Pandas

So far, we have learned, how to add a legend to the plot and how to customize the legend using plt.legend() function. Now we will see the legend which, will add the outside of the plot in Pandas using legend() function. Pass bbox_to_anchor into legend() function, it will create the legend outside of the plot.


# Add legend outside of the plot 
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))

Frequently Asked Questions on Add Plot Legends in Pandas

How do I add legends to a Pandas plot?

To add legends to a Pandas plot, you can use the legend method on the AxesSubplot object returned by the plot function. Provide a list of labels for the legend corresponding to the columns in your DataFrame.

Can I customize the legend in a Pandas plot?

You can customize the legend in various ways. The legend method accepts parameters for customization

How do I add a legend title in Pandas plot?

To add a title to the legend in a Pandas plot, you can use the title parameter of the legend method. For example, the title='Variables' argument is passed to the legend method, which sets the title of the legend to ‘Variables’. Adjust the title according to your specific use case.

Can I change the location of the legend in a Pandas plot?

You can change the location of the legend in a Pandas plot using the loc parameter of the legend method. The loc parameter allows you to specify the location of the legend in relation to the plot.

What if I have a Seaborn plot with Pandas? Can I still add legends?

You can add legends to Seaborn plots created from Pandas DataFrames. Seaborn is built on top of Matplotlib, and the process of adding legends is similar. After creating the Seaborn plot, you can use Matplotlib’s legend method to add a legend.

Conclusion

In this article, I have explained how to add a legend to the plot bar using legend() and using its syntax and Parameters how we can change the location of the legend in different ways and also explain how we can customize the legend using various legend parameters with multiple visualization examples.

Happy learning !!

References

Vijetha

Vijetha is an experienced technical writer with a strong command of various programming languages. She has had the opportunity to work extensively with a diverse range of technologies, including Python, Pandas, NumPy, and R. Throughout her career, Vijetha has consistently exhibited a remarkable ability to comprehend intricate technical details and adeptly translate them into accessible and understandable materials. Follow me at Linkedin.

Leave a Reply