Put legend outside plot matplotlib

In this Python tutorial, we will discuss Put legend outside plot matplotlib in python. Here we will cover different examples related to legend outside plot using matplotlib. And we will also cover the following topics:

  • Put legend outside plot matplotlib
  • Matplotlib set legend outside plot
  • Matplotlib set legend center-left outside plot
  • Matplotlib set legend lower-center outside plot
  • Matplotlib set subplots legend outside
  • Sns put legend outside plot matplotlib
  • Sns set legend upper-left outside plot

Put legend outside plot matplotlib

In this section, we learn about how to put legend outside plot in matplotlib in Python. Now before starting the topic firstly, we have to understand what does “legend” means.

Legend is an area that outlines the elements of the graph.

The following steps are used to plot legend outside in matplotlib are outlined below:

  • Defining Libraries: Import the important libraries which are required (For data creation and manipulation: Numpy and Pandas, For data visualization: pyplot from matplotlib).
  • Define X and Y: Define the data coordinated values used for the x-axis and y-axis.
  • Plot chart or figure: By using bar()pie()scatter()plot(), etc methods we can draw a plot.
  • Add Legend Outside: By using the legend() method we can add a legend to a plot. To specify it outside the plot use the bbox_to_anchor attribute of the legend() function.
  • Generate a Plot: Use the show() method to visualize the plot on the user’s windows.

Read Python Matplotlib tick_params

Matplotlib set legend outside plot

In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it.

The syntax to set legend outside is as given below:

matplotlib.pyplot.legend(bbox_to_anchor=(x,y))

We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.

Let’s see an example to set legend outside the plot:

# Import Library

import numpy as np
import matplotlib.pyplot as plt
   
# Define Data

x = [0, 1, 2, 3, 4, 5]    
y1 = [0, 2, 4, 6, 8, 10]
y2 = [0, 3, 6, 9, 12, 15]
   
# Plot graph

plt.plot(y1, label ="y = 2x")
plt.plot(y2, label ="y = 3x")
   
# Add legend

plt.legend(bbox_to_anchor =(0.65, 1.25))
   
# Show plot

plt.show()
  • In the above example, firstly we import the libraries such as numpy and matplotlib.
  • Next, we define the data and by using plt.plot() method we plot graphs and labels.
  • plt.legend() method is used to add a legend to the plot and we pass the bbox_to_anchor attribute and set its x and y coordinate values.
matplotlib set legend outside plot
” Legend outside the plot “

Also, check: Matplotlib change background color

Matplotlib set legend center-left outside plot

Here we are going to learn how to set legend outside of the plot at the center-left location.

The syntax for this is as given below:

matplotlib.pyplot.legend(bbox_to_anchor=(x,y) , loc='center left')

Let’s have a look at an example:

# Import libraries

import matplotlib.pyplot as plt
import pandas as pd

# Define Data

df = pd.DataFrame({
    'Maths': [12, 15, 10, 3, 1, 5],
    'Science': [15, 10, 5, 4, 3, 6],
    'Computers':[20, 12, 5, 3, 5, 2]
})

labels = ['A','B','C','D','E','Fail']

# Plot bar chart

ax = df.plot(stacked=True, kind='bar')
   
# Set Tick labels

ax.set_xticklabels(labels,rotation='horizontal')

ax.legend(title='SUBJECT',title_fontsize=30,loc='center left', bbox_to_anchor=(1, 0.5))

# Display chart


plt.show()
  • In the above example, we import matplotlib.pyplot, and pandas library.
  • After this, we use the pandas DataFrame() method to define labels and data coordinates and we use the plot() method to draw a bar chart.
  • By using the set_xticklabels() method we set x label and also set its rotation to horizontal.
  • Then we use the ax.legend() method to set the title of the legend and pass the title_fontsize argument and set its value to 30.
  • We also pass the loc and bbox_to_anchor=(x,y) attribute and set its value to center left and 1, 0.5 respectively.
matplotlib set legend center left outside plot
” Legend at center-left “

Read: Matplotlib scatter marker

Matplotlib set legend upper-center outside plot

Here we are going to learn how to set legend outside of the plot at the lower-center location.

The syntax for this is as below:

matplotlib.pyplot.legend(bbox_to_anchor=(x,y) , loc='lower center') 

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt
   
# Define Data

x = [0, 1, 2, 3, 4, 5]    

y = [0, 5, 10, 15, 20, 25]
   
# Plot graph

plt.plot(y1, label ="y = 5x")
 
# Add legend

plt.legend(bbox_to_anchor =(0.5,-0.27), loc='lower center')
   
# Show plot

plt.show()
  • In the above plot, we import numpy and matplotlib.pyplot library.
  • After this, we define data and plot the graph by using the plt.plot() method.
  • By using plt.legend() method, we set the legend and we pass the bbox_to_anchor and loc attribute set its values to (0.5, -0.27) and lower center respectively.
matplotlib set legend upper center outside plot
” Legend at the lower center “

Read: Matplotlib dashed line

Matplotlib set subplots legend outside

Multiple plots in one figure are known as subplots. Here we are going to plot subplots and define legend outside the plot.

Let’s see an example related to this:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt
  
# Define Data

x = np.linspace(10, 5, 1000)

# Plot subplots


fig, ax = plt.subplots(2, 2)
for i in range(2):
    ax[1][i].plot(x, np.tan(x+i),
                 label = "y=tan(x+{})".format(i))
      
    ax[0][i].plot(x, np.tan(x+i), 
                  label = "y=tan(x+{})".format(i))
      
# Add legends

fig.legend(bbox_to_anchor=(1.3, 0.6))
  
# Show plot

fig.tight_layout()  
plt.show()
  • Firstly, we import the numpy and matplotlib library. Next, we define data using the linespace() method of numpy.
  • After this we plot subplots and use “for loop” and define a tan function to plot the subplots.
  • By using the fig.legend() method we add a legend to the plot and pass the bbox_to_anchor attribute to it.
  • We use the fig.tight_layout() and plt.show() method to automatically adjust and visualize the graph respectively.
matplotlib set subplots legend outside
” Legend outside the subplots “

Read: Matplotlib plot_date

Sns put legend outside plot matplotlib

Here we are going to plot legends outside the plot using Seaborn in matplotlib in Python.

If Seaborn is not installed in your system the easiest way to install it is the command line terminal.

Syntax to install:

# Command to install Seaborn

pip install seaborn 

Let’s see an example of seaborn legend outside the plot:

# Import Libraries

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Define Data

df = pd.DataFrame({
    'X': [12, 15, 10, 3, 1, 5],
    'Y': [15, 10, 5, 4, 3, 6],
    'Label':['Pass','Pass','Fail','Pass','Fail','Fail']
})

# Scatter plot

sns.scatterplot(data=df, x='X',y='Y', hue='Label')

# Legend plot

plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left')

# Show

plt.show()
  • Firstly we import the matplotlib.pyplot, pandas, and seaborn library.
  • After this, we define the data using the DataFrame() method.
  • Then use sns.scatterplot() method to plot the seaborn graph and use the plt.legend() method to add legend outside the plot.
sns put legend outside plot matplotlib
” Seaborn plot “

Read: Matplotlib log log plot

Sns set legend upper-left outside plot

Here we are going to learn how you can set legend outside at the upper left corner in the Seaborn plot in matplotlib.

Example:

# Import libraries

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Define Data

df = pd.DataFrame({
    'X': [12, 15, 10, 3, 1, 5],
    'Y': [15, 10, 5, 4, 3, 6],
    'Label':['Pass','Pass','Fail','Pass','Fail','Fail']
})

# Scatter plot

sns.lineplot(data=df, x='X',y='Y', hue='Label')

# Legend plot

plt.legend(bbox_to_anchor=(1.02, 0.15), loc='upper left', borderaxespad=0)

# Show

plt.show()
  • Here we use sns.lineplot() method to plot seaborn graph.
  • Use plt.legend() method to add a legend, pass the bbox_to_anchor argument and loc argument to it.
  • Set values of the arguments as (1.02, 0.15) and upper left respectively.
sns set legend upper left outside plot
” Upper-left legend outside the sns plot “

Also, take a look at some more articles on Matplotlib.

In this Python tutorial, we have discussed the “Put legend outside plot matplotlib” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Put legend outside plot matplotlib
  • Matplotlib set legend outside plot
  • Matplotlib set legend center-left outside plot
  • Matplotlib set legend lower-center outside plot
  • Matplotlib set subplots legend outside
  • Sns put legend outside plot matplotlib
  • Sns set legend upper-left outside plot