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
  • Matplotlib legend outside plot cut off
  • Matplotlib legend outside plot right
  • Matplotlib legend outside below plot
  • Legend outside plot matplotlib tight_layout

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 “

Read: What is add_axes matplotlib

Matplotlib legend outside plot cut off

Here we’ll learn how to prevent a legend box from being cropped using matplotlib. To prevent the legend from being cropped, we’ll use bbox_extra_artists and bbox_inches.

  • The list of Artists that will be considered when the tight bbox is calculated is specified by bbox_extra_artists.
  • If bbox_inches is set to tight, the figure’s tight bbox will be generated.

Let’s see an example:

# Import Libraries


import matplotlib.pyplot as plt
import numpy as np

# Define Data


x = np.linspace(0, 10, 2)
y1 = np.cos(x)
y2 = np.exp(x)

# Plot

plt.plot(x, y1, label="cos(x)")
plt.plot(x, y2, label="exp(x)")

# Legend 

legend_outside = plt.legend(bbox_to_anchor=(1.05, 1.0), 
                            loc='upper left')

# Savefig


plt.savefig('outside_legend.png', 
            dpi=150, 
            format='png', 
            bbox_extra_artists=(legend_outside,), 
            bbox_inches='tight')

# Display

plt.show()
  • Import matplotlib.pyplot as plt for data visualization.
  • Next, import numpy as np for data creation.
  • Then, define data coordinates by using linspace(), cos() and exp() method.
  • To plot the graph, we use the plot() function.
  • To add the legend outside the plot, we use the legend() method and pass the bbox_to_anchor parameter to it.
  • Next, we use the savefig() function to save the plot as png.
  • To prevent the legend from being cropped, we pass the bbox_extra_artists and bbox_inches as a parameter to savefig() function.
  • To display the plot on the user’s screen, we use the show() function.
matplotlib legend outside plot being cut off
Matplotlib legend outside plot being cut off

Read: Matplotlib 2d surface plot

Matplotlib legend outside plot right

In this section, we’ll learn to set the position of legend to the right side of the plot. To set the location to right, we pass the loc parameter to the legend() method. The value of loc could be a number or a string.

The number value to set right is 5 and the string value is right.

Let’s see an example:

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.linspace(0, 30, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Plot

plt.plot(x, y1, label='Sin')
plt.plot(x, y2, label='Cos')

# Legend 


legend_outside = plt.legend(bbox_to_anchor=(1.20,0.89),                          
                            loc='right')

# Display

plt.show()
  • Firstly, we import matplotlib.pyplot, and numpy libraries.
  • To define the data coordinates, use linspace(), sin(), and cos() function.
  • To plot the line graph, we use the plot() function.
  • To add a legend to the plot pass the label parameter to plot() function.
  • To set legend outside, use legend() function and pass loc parameter to it and set to the right as the string value.
matplotlib legend outside plot right
Matplotlib legend outside plot right

Read: Matplotlib time series plot

Matplotlib legend outside below plot

In this section, we’ll learn to set legend box below the plot. We can set the legend to lower left, lower right, and the lower center also.

Syntax:

matplotlib.pyplot.legend(bbox_to_anchor, loc = 'lower right'| 
                         'lower left' | 'lower center')

You can also loc number instead of loc string as 3 for lower left, 4 for lower right, and 8 for the lower center.

Let’s see examples:

Example #1

Here we set legend to lower right location.

# Import Library


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


name = ['Ava', 'Noah', 'Charlotte', 'Robert', 'Patricia']
weight_kg = [45, 60, 50, 75, 53]
height_cm = [162, 175, 155, 170, 168]

# Plot

plt.plot(name, weight_kg, marker ='o', label='Weight')
plt.plot(name, height_cm, marker='o', label='Height')

# Legend

plt.legend(bbox_to_anchor=(0.98,-0.3), loc='lower right')

# Display

plt.show()
  • Firstly, import necessary libraries such as numpy and matplotlib.pyplot.
  • Next, define data coordinates.
  • To plot a line chart, use the plot() function.
  • To add a legend to the plot, use legend() method.
  • To set legend outside the plot, pass bbox_to_anchor parameter and to set its location to lower right, we also loc parameter.
matplotlib legend outside below plot
Matplotlib legend outside below plot

Example #2

# Import Library

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


year = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
profit = [80, 60, 50, 95, 75, 63, 35, 90, 68, 78]
loss = [20, 40, 50, 5, 25, 37, 65, 10, 32, 22]

# Plot

plt.scatter(year, profit, label='Profit')
plt.scatter(year, loss, label='Loss')

# Set axis

plt.xlim(0, 12)

# Legend

plt.legend(bbox_to_anchor=(-0.01,-0.3), loc=3)

# Display

plt.show()

Here, we set the legend to the lower-left location of the plot, by using the legend() function.

matplotlib legend outside lower plot
Matplotlib legend outside lower plot

Read: Matplotlib set y axis range

Legend outside plot matplotlib tight_layout

In this section, we’ll learn to plot a graph with outside legend using matplotlib.

Let’s see an example:

# Import Library


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

name = ['Ava', 'Noah', 'Charlotte', 'Robert', 'Patricia']
weight_kg = [45, 60, 50, 75, 53]
height_cm = [162, 175, 155, 170, 168]

# Plot

plt.plot(name, weight_kg, marker ='o', label='Weight')
plt.plot(name, height_cm, marker='o', label='Height')

# Legend

plt.legend(bbox_to_anchor=(0.60,-0.1), loc=1)

# Auto adjust

plt.tight_layout()

# Save Plot

plt.savefig('Legend Plot.png', format='png')

# Display

plt.show()
  • Here, we use legend() function to add legend.
  • To add legend outside the plot, we pass bbox_to_anchor parameter.
  • To prevent legend from cut off, we use tight_layout() function.
  • To save the plot, we use savefig() function.
  • To show the plot on user’s screen, we use show() function.
legend outside plot matplotlib tight_layout
Legend outside plot matplotlib tight_layout

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
  • Matplotlib legend outside plot cut off
  • Matplotlib legend outside plot right
  • Matplotlib legend outside below plot
  • Legend outside plot matplotlib tight_layout