How to Place the Legend Outside the Plot Using Matplotlib?

Add A Legend Outside The Plot

Legend in terms of a graph or any plot provides the description of the elements inside the plot. These elements can be the entities plotted on the graph, their scales, their colors, and so on. A legend is usually a box placed at the top right or left corner of the graph, but its location can be customized.

The matplotlib library is a powerful, open-source tool for data visualization. This library includes a number of plots including 3D plots for visualizing the data which helps us to understand and analyze the data in a better way. We can even visualize a data frame or a series of the Pandas library with Matplotlib.

The matplotlib has many functions to work with data visualization. It has a function called legend() that specifically assigns a legend to the plot of your data.

Visit this article to know more about the types of plots available in Matplotlib.

Prerequisites

Before we move on to using the Matplotlib library, we need to first ensure that it is installed in our systems. You can install the library using the pip command as shown below.

Using the terminal
pip install matplotlib
Installing in any notebook such as Colab or Jupyter
! pip install matplotlib
Using the conda command prompt
conda install -c conda-forge matplotlib

What Is a Legend?

A legend is a small box that describes or gives meaning to the plot of your data. It is usually placed in the top right or left corner of the plot, but we can customize the location and the appearance of the legend using the legend function.

Let us see one example of this method using the syntax given below.

matplotlib.pyplot.legend(*args, **kwargs)

The important parameters of this function are listed and explained below.

import matplotlib.pyplot as plt
x=[2,4,6,8,10]
y=[1,3,5,7,11]
z=[2,3,5,7,11]
plt.plot(x, y, label='Even&Odd')
plt.plot(x, z, label='Even&Prime')
plt.plot(y,z,label='Odd&Prime')
plt.legend(title='LEGEND')
plt.title('Even,Odd&Prime Numbers')
plt.show()

Once you have installed the matplotlib library in your environment. You can import it using the first line of the code.

We are creating three lists that contain even numbers, odd numbers, and prime numbers. They are named x,y, and z respectively.

Next, we are calling the plot function three times to plot the combination of even-odd numbers( x and y), even-prime numbers(x and z), and odd-prime numbers(y and z) one after the other. These plots are also named using the label property.

The legend function is called which displays the color of the plot and the label associated with it. We are also specifying the title of the legend.

The title is used to give a name to the entire plot or graph.

The show function is used to display the graph.

Legend With Title
Legend With Title

How to Place the Legend Outside the Plot?

In the previous example we have seen how by default, the legend appears inside the plot or graph boundaries. But there is a way to place the legend outside the plot using some techniques.

Related: Visit this article to know how to use the index of a data frame as the label for X-axis.

Using the Bbox to Anchor

This property is an attribute of the legend function used to place the box in correspondence to its location.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
z = [1, 3, 5, 7, 9]
plt.plot(x, y, label='Line 1')
plt.plot(y, z, label='Line 2')
plt.legend( bbox_to_anchor=(1.1,1.05),shadow=True,title='Legend')
plt.title('Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

We are importing the matplotlib library as plt in the first line.

Next, we are creating three lists named x,y, and z that contain random elements.

Next, we are plotting two lines – x with respect to y and y with respect to z. These lines are given labels with the help of label.

The legend function is used to create a legend that takes the argument bbox_to_anchor which has some coordinates to place the legend. The shadow property is used to create a shadow effect for the box. We can also provide the title to the legend using title.

The next three lines are used to provide the title of the graph and names for the X and Y axes.

The show method is used to display the plot.

Using Bbox To Place The Legend Outside The Plot
Using Bbox To Place The Legend Outside The Plot

Placing the Legend on the Border

We can place the legend where we want if we can know the correct coordinates to use to get the desired output.

Let us see how we can put a legend on the border of the graph.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y= [2, 4, 6, 8, 10]
z = [1,11,3,4,7]
plt.plot(x, y, label='Line 1')
plt.plot(x, z, label='Line 2')
plt.legend(bbox_to_anchor=(0.9,0.8),title='Legend',shadow=True)
plt.title('Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

The first step is to import the matplotlib library.

The next three lines create three different lists named x,y, and z that have some numbers.

We are plotting two lines- x with respect to y and x with respect to z. These lines are plotted using the plot function.

Next, we are creating a legend for this graph using the bbox_to_anchor property. The coordinates we chose are (0.9,0.8) which results in the legend on the right side border in the center. The shadow property is used to create a shadow effect for the box.

The next three lines create a title for the graph and also name the x and y axes.

The show method is used to display the graph as output.

Legend On The Border
Legend On The Border

Using the Loc Property With Bbox

In this example, we are going to use the loc attribute along with the bbox_to_anchor to create a unique legend on top of the graph.

import pandas as pd
import matplotlib.pyplot as plt
groc = {'Food': ['Tacos', 'Mac and Cheese', 'Carbonara', 'Lasagna', 'Croissant'],
        'Calories': [226, 164, 574, 135, 406],
        'Quantity':[3,1,2,3,1]}
df = pd.DataFrame(groc)
plt.plot(df['Food'], df['Calories'], label='F&C')
plt.plot(df['Food'], df['Quantity'], label='F&Q')
plt.title('Different foods and their calories')
plt.xlabel('Food Item')
plt.ylabel('Calories')
plt.legend(loc='center right', bbox_to_anchor=(0.3,1.1),ncol=2,fancybox=True)
plt.show()

We are going to plot a data frame and for that, we need to first import the Pandas library. We are also importing the matplotlib library in the next line.

A dictionary called groc is created that contains a few food items, their respective calories, and the quantity purchased. This dictionary is converted to a data frame with the help of the method pd.DataFrame.

We are plotting the Food column with respect to Calories in the first plot and Food with respect to Quantity in the second plot. Their respective labels are given.

Next, we are specifying the title and the labels for the x and y axes. The legend function is used to create a box that contains the description of the graph, We are using the loc property which is given to be center right and the bbox coordinates used are (0.3,1.1). The ncol parameter is used to define how many columns the legend box should have. In this case, it is 2. The fancybox is used to create rounded edges for the box.

Finally, the show method is used to display the graph.

Legend Using Bbox And Loc
Legend Using Bbox And Loc

To conclude, we have seen what is the legend of a graph in matplotlib. It is a box that describes the elements of the graph such as the type of plot, the elements being plotted, and so on. By default, this legend appears inside the plot boundary when using the legend function of the matplotlib.

The matplotlib is a data visualization tool consisting of a number of plots to help us visualize data in a better way.
We have seen the example of a simple legend by plotting three plots: Even-Odd numbers, Even-Prime numbers, and Odd-Prime numbers.
We created a legend for this plot including the title for it.

Coming to placing the legend outside the plot, we have seen three approaches to it.
In the first method, we used the bbox property of the legend function to define a pair of coordinates that place the legend outside the graph boundary with a shadow effect and title.

In the next method, we used the same bbox_to_anchor property and different coordinates that place the legend on the right side border just above the center.

In the last example, we used the loc parameter of the legend function along with the bbox property. We plotted a data frame of three different columns inside it. The ncol parameter is used to define the number of columns to appear in the legend. We also gave a rounded edge to the box with the help of fancybox.

These results can be customized and fun to experiment with. Have fun experimenting with the above examples!

References

You can find more about the legend function here.

Refer to this StackOverflow answer chain for more examples of placing legends outside the plot using matplotlib.

lib