Matplotlib scatter plot legend

In this Matplotlib tutorial, we will discuss Matplotlib Scatter Plot Legend. Here we will cover different examples related to the scatter plot legend using matplotlib. And we will also cover the following topics:

  • Matplotlib scatter plot legend
  • Matplotlib scatter plot legend example
  • Matplotlib scatter plot legend position
  • Python scatter plot legend outside
  • Matplotlib scatter plot legend title
  • Matplotlib scatter plot legend facecolor
  • Matplotlib scatter plot show legend
  • Python seaborn scatter plot legend outside
  • Matplotlib scatter plot legend size
  • Python scatter plot legend marker size
  • Matplotlib scatter plot legend by color

Matplotlib scatter plot legend

In this section, we learn about how to add a legend to the Scatter Plot in matplotlib in Python. Now before starting the topic firstly, we have to understand what does “legend” means and how “scatter plot created”.

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

Scatter Plot is a graph in which the values of two variables are plotted along two axes. It represent the reletionship between two variables in a data-set.

The following steps are used to plot scatter graph and add a legend to it are outlined below:

  • Defining Libraries: Import the important libraries which are required for data creation and manipulation (Numpy and Pandas) and for data visualization ( pyplot from matplotlib).
  • Define X and Y: Define the data coordinates values used for the x-axis and y-axis.
  • Plot scatter graph: By using the scatter() method we can draw a plot.
  • Add Legend: By using the legend() method we can add a legend to a plot.
  • Generate a Plot: Use the show() method to visualize the plot on the user’s windows.

Matplotlib scatter plot legend example

We can add a legend to the plot using the matplotlib module. We use the matplotlib.pyplot.legend() method to mark out and label the elements of the graph.

The syntax to add a legend to the plot:

matplotlib.pyplot.legend(["Title"], ncol=1, loc="upper left", bbox_to_anchor=(1,1))

The parameters used above are described below:

  • title: specify the label you want to add.
  • ncol: represent the number of columns in legend.
  • loc: represent the location of the legend.
  • bbox_to_anchor: represent the coordinates of legend on the graph.

Let’s see an example of a scatter plot with the legend:

# Import libraries

import matplotlib.pyplot as plt
 
# Define Data

x =  [1, 2, 3, 4, 5]
y1 = [5, 10, 15, 20, 25]
y2 = [10, 20, 30, 40, 50]
 
# Scatter Plot

plt.scatter(x, y1)
plt.scatter(x, y2)

# Add legend

plt.legend(["x*5" , "x*10"])

# Display

plt.show()
  • In the above example, we import the pyplot module of matplotlib.
  • After this, we define data coodinates.
  • plt.scatter() method is used to plot scatter graph.
  • plt.legend() method is used to add a legend to the plot.
  • plt.show() method is used to visualize the plot on the user’s screen.
matplotlib scatter plot legend example
plt.legend()

Also, read: Matplotlib save as png

Matplotlib scatter plot legend position

Here we are going to learn how to add legend at a specific position of scatter plot. There are different locations available in matplotlib to place a legend.

Let’s see different positions of legend with examples:

Upper Right Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the upper right.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='upper right')

Example:

# Import libraries

import matplotlib.pyplot as plt
 
# Define Data

x =  [1, 2, 3, 4, 5]
y1 = [5, 10, 15, 13.6, 16]
y2 = [10, 20, 16.3, 4.8, 9]
 
# Scatter Plot

plt.scatter(x, y1, s=50)
plt.scatter(x, y2, s=50)

# Add legend

plt.legend(["Label-1" , "Label-2"], loc= 'upper right')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot and we pass loc as a parameter and set its value to the upper right.
matplotlib scatter plot legend position
plt.legend(loc=’upper right’)

Upper Left Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the upper left.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='upper left')

Example:

# Import library

import matplotlib.pyplot as plt
 
# Define Data

x =  [1, 2, 3, 4, 5]
y1 = [5, 10, 15, 20, 25]
y2 = [10, 20, 30, 40, 50]
 
# Scatter Plot

plt.scatter(x, y1)
plt.scatter(x, y2)

# Add legend

plt.legend(["x*5" , "x*10"], loc='upper left')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot and we pass loc as a parameter and set its value to the upper left.
matplotlib scatter plot legend set position
plt.legend(loc=upper left)

Lower left Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the lower left.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='lower left')

Example:

# Import library

import matplotlib.pyplot as plt
 
# Define Data

x =  [1, 2, 3, 4, 5]
y1 = [5, 10, 15, 13.6, 16]
y2 = [10, 20, 16.3, 4.8, 9]
 
# Scatter Plot

plt.scatter(x, y1, s=150, zorder=1.5)
plt.scatter(x, y2, s=150, zorder=1.5)

# Add legend

plt.legend(["Label-1" , "Label-2"], loc= 'lower left')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot and we pass loc as a parameter and set its value to the lower left.
  • We also use the zorder parameter so that we get legend above the scatter dots.
matplotlib scatter plot legend place legend
plt.legend(loc=’lower left’)

Read: Matplotlib savefig blank image

Lower Right Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the lower right.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='lower right')

Example:

# Import library

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

x = np.arange(0, 20, 0.2)
y1 = np.sin(x)
y2 = np.cos(x)
 
# Scatter Plot

plt.scatter(x, y1, s=150, zorder=1.5)
plt.scatter(x, y2, s=150, zorder=1.5)

# Add legend

plt.legend(["Label-1" , "Label-2"], loc= 'lower right')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot.
  • We pass loc as a parameter and set its value to the lower right.
  • We also use the zorder parameter to get a legend above the scatter dots.
matplotlib scatter plot legend put position
plt.legend(loc= ‘lower right’)

Right Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the right.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='right')

Example:

# Import library

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

x = np.random.randint(450,size=(80))
y1 = np.random.randint(260, size=(80))
y2 = np.random.randint(490, size=(80))

# Scatter Plot

plt.scatter(x, y1, s=150, zorder=1.5)
plt.scatter(x, y2, s=150, zorder=1.5)

# Add legend

plt.legend(["Label-1" , "Label-2"], loc= 'right')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot and we also use the zorder parameter to get a legend above the scatter dots.
  • We pass loc as a parameter and set its value to the right.
matplotlib scatter plot legend adjust position
plt.legend(loc=’right’)

Read: Matplotlib bar chart labels

Center Left Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the center-left.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='center left')

Example:

# Import library

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

x = np.arange(0, 20, 0.2)
y1 = np.sin(x)
y2 = np.cos(x)
 
# Scatter Plot

plt.scatter(x, y1, s=150, zorder=1.5)
plt.scatter(x, y2, s=150, zorder=1.5)

# Add legend

plt.legend(["Sin X" , "Cos X"], loc= 'center left')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot and we also use the zorder parameter to get a legend above the to scatter dots.
  • We pass loc as a parameter and set its value to the center left.
matplotlib scatter plot legend locate position
plt.legend(loc=’center left’)

Center Right Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the center-right.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='center right')

Example:

# Import library

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

x = np.arange(0, 20, 0.2)
y1 = np.sin(x)
y2 = np.exp(x)
 
# Scatter Plot

plt.scatter(x, y1, zorder=1.5)
plt.scatter(x, y2, zorder=1.5)

# Add legend

plt.legend(["Sin X" , "Exp X"], loc= 'center right')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot
  • We also use the zorder parameter to get a legend above the to scatter dots.
  • We pass loc as a parameter and set its value to the center right.
matplotlib scatter plot legend set up position
plt.legend(loc=’center right’)

Read: Matplotlib plot error bars

Lower Center Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the lower center.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='lower center')

Example:

# Import library

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

x = np.arange(0, 20, 0.2)
y1 = np.cos(x)
y2 = np.exp(x)
 
# Scatter Plot

plt.scatter(x, y1, zorder=1.5)
plt.scatter(x, y2, zorder=1.5)

# Add legend

plt.legend(["Cos X" , "Exp X"], loc= 'lower center')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot and we pass loc as a parameter and set its value to the lower center.
matplotlib scatter plot legend location
plt.legend(loc=’lower center’)

Upper Center Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the upper center.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='upper center')

Example:

# Import library

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

x = np.linspace(0,15,150)
y1 = np.sin(x)
y2 = np.cos(x)

# Scatter Plot

plt.scatter(x, y1, zorder=1.5)
plt.scatter(x, y2, zorder=1.5)

# Add legend

plt.legend(["Sin X" , "Cos X"], loc= 'upper center')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot and we pass loc as a parameter and set its value to the upper center.
matplotlib scatter plot position of legend
plt.legend(loc=’upper center’)

Read: Matplotlib rotate tick labels

Center Position of Legend

We use the legend() method to add a legend and pass the loc parameter to set the location of the legend. Here we set its positions to the center.

The syntax is given below:

matplotlib.pyplot.legend(["Title"], loc='center')

Example:

# Import library

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

x = np.linspace(0,15,150)
y1 = np.tan(x)
y2 = np.exp(4*x)

# Scatter Plot

plt.scatter(x, y1, zorder=1.5)
plt.scatter(x, y2, zorder=1.5)

# Add legend

plt.legend(["Tan X" , "Exp X"], loc= 'center')

# Display

plt.show()
  • In the above example, we use the legend() method to add a legend to the scatter plot
  • We also use the zorder parameter to get a legend above the to scatter dots.
  • We pass loc as a parameter and set its value to the center.
matplotlib scatter plot set legend position
plt.legend(loc=’center’)

Read: Matplotlib change background color

Python scatter plot legend outside

Here we are going to learn how to add legend outside the plot in the Matplotlib. By using the bbox_to_anchor we can place the legend outside the plot.

bbox_to_anchor specifies the legend box’s location. bbox means bounding box.

The syntax to add legend outside the plot is given below:

matplotlib.pyplot.legend(['Legend'], bbox_to_anchor=(x, y, width, height), loc= )

The parameters used above are as follow:

  • x: specify legend box location at x-axes.
  • y: specify legend box location at y-axes.
  • width: specify the width of the legend box.
  • height: specify the height of the legend box.
  • loc: specify the location of the legend box.

Let’s have a look at examples where we plot legend outside the plot:

Example #1

# Import library

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

x = np.arange(0, 20, 0.2)
y1 = np.sin(x)
y2 = np.cos(x)
 
# Scatter Plot

plt.scatter(x, y1, s=100)
plt.scatter(x, y2, s=100)

# Add legend outside the plot

plt.legend(['Sin X', 'Cos X'], bbox_to_anchor=(1.22,0.5), loc= 'upper right')

# Display

plt.show()
  • In the above example, we import pyplot and numpy matplotlib modules.
  • After this we define data using arange(), sin(), and cos() methods of numpy.
  • plt.scatter() method is used to plot scatter graph.
  • plt.legend() method is used to add a legend to the plot and we pass the bbox_to_anchor parameter to specify legend position outside of the plot.
  • We also pass loc as arguemnt to specify the position of the legend.
  • plt.show() method is used to visualize the plot on the user’s screen.
python scatter plot legend outside
plt.legend(bbox_to_anchor=())

Example #2

# Import library


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


x = [14, 24, 43, 47, 54, 66, 74, 89, 12,
      44, 1, 2, 3, 4, 5, 9, 8, 7, 6, 5]
  
y1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 6, 3,
      5, 2, 4, 1, 8, 7, 0, 5]
  
y2 = [9, 6, 3, 5, 2, 4, 1, 8, 7, 0, 1, 2, 
      3, 4, 5, 6, 7, 8, 9, 0]


# Scatter Plot


plt.scatter(x, y1, s=150)
plt.scatter(x, y2, s=150)

# Add legend


plt.legend(["Label-1" , "Label-2"], bbox_to_anchor=(-0.1, 0.75))

# Display


plt.show()

Here we use plt.legend() method with bbox_to_anchor argument to add a legend outside the plot.

python scatter plot set legend outside
bbox_to_anchor()

Read: Matplotlib scatter marker

Matplotlib scatter plot legend title

Here we are going to learn how we can add a title to a legend in matplotlib.

To add a title we have to pass the title as an argument to the legend() method and we can also set the size of the title by passing title_fontszie as a parameter.

The syntax is given below:

matplotlib.pyplot.legend(title= , title_fontsize= , ['Labels'] , loc= )

Let’s see an example of a legend with the title:

# Import library


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


x = np.arange(0, 30, 0.5)
y1 = np.sin(x)
y2 = np.cos(x)
 
# Scatter Plot


plt.scatter(x, y1)
plt.scatter(x, y2)

# Add legend with title


plt.legend(['Sin X', 'Cos X'], title='LABELS',  
           title_fontsize= 25,
 loc= 'best')

# Display


plt.show()
  • In the above example, to add a legend in the plot we use plt.legend() method.
  • We pass label, title, title_fontsize, loc as a parameter.
matplotlib scatter plot legend title
“Legend with Title”

Read: Matplotlib dashed line

Matplotlib scatter plot legend facecolor

Here we are going to learn how we can change the color of legend in scatter plot in matplotlib. To change the color pass the parameter facecolor to legend() method.

The syntax to change facecolor of the legend of scatter plot:

matplotlib.pyplot.legend(['label'], facecolor=None)

The above parameters are:

  • label: define the label.
  • facecolor: specify the facecolor of the legend.

Let’s see an example:

# Import library


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


x = np.linspace(0,10,25)
y1 = np.cos(x)
y2 = np.sin(x)

# Scatter Plot


plt.scatter(x, y1)
plt.scatter(x, y2)

# Add legend and change color


plt.legend(["Cos X" , "Sin X"], loc= 'lower left', 
            facecolor='yellow')

# Display


plt.show()

Here we use a plot.legend() method and pass facecolor as a parameter to set its facecolor.

matplotlib sactter plot legend facecolor
” Legend With Facecolor “

Read: Matplotlib log log plot

Matplotlib scatter plot show legend

Here we learn how to show legend in a scatter plot. Sometimes user defines labels in the plotting methods and doesn’t use the legend() method. In that case, the legend is not shown.

Let’s see an example:

Example #1

Here is the example where we define the label in scatter() method and legend() method is not used.

# Import library


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


x =  np.random.randint(100,size=(80))
y1 = np.random.randint(150, size=(80))
y2 = np.random.randint(200, size=(80))
 
# Scatter Plot and define label


plt.scatter(x, y1, label='LABEL-1')
plt.scatter(x, y2, label='LABEL-2')

# Display


plt.show()

In the above example, we use plt.scatter() method to plot scatter graph and we pass label as a parameter to define legend labels.

matplotlib scatter plot show legend
plt.scatter(label= )

Here we see the legend is not shown in this plot.

Example #2

Here is the example where we define the label in scatter() method and legend() method is used.

# Import library


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


x = np.random.randint(100,size=(80))
y1 = np.random.randint(150, size=(80))
y2 = np.random.randint(200, size=(80))
 
# Scatter Plot and define label


plt.scatter(x, y1, label='LABEL-1')
plt.scatter(x, y2, label='LABEL-2')

# Add legend


plt.legend()

# Display


plt.show()

In the above example, we use plt.scatter() method to plot scatter graph and we pass label as a parameter to define legend labels. And we use plt.legend() method to show legend.

matplotlib scatter plot shown legend
plt.legend()

Here we see that legend is shown in the scatter plot by using plt.legend() method.

Read: Stacked Bar Chart Matplotlib

Python seaborn scatter plot legend outside

Here we learn how to plot seaborn scatter and add legend outside.

To plot seaborn scatter plot use sns.scatterplot() method and we use plt.legend() method to add legend.

Let’s have a look at an example:

# Import library


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

# Define data


df = pd.DataFrame({'Maths': [5, 12, 15, 13, 10, 9, 8, 6, 15, 
                            20, 16, 13, 15],
                   'Science': [3, 6, 9, 2, 6, 7, 3, 1, 2.5,  
                               6.9, 4, 2, 1],
                   'favour':  
                   ['Like','Dislike','Dislike','Like',      
                    'Like', 'Like','Dislike', 
                    'Dislike','Dislike', 'Like', 'Like', 
                    'Like', 'Dislike']})

# create scatterplot

sns.scatterplot(data=df, x='Maths', y='Science', hue='favour')

# Legend outside

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

# Display

plt.show()
  • In the above example, we import pandas, seaborn, and pyplot library.
  • Then we define data by using DataFrame.
  • After this, we use sns.scatterplot() method to create a seaborn scatter plot.
  • plt.legend() method is used to add a legend to the plot.
python seaborn scatter plot legend outside
Seaborn Scatter Plot With Legend

Read: Matplotlib two y axes

Matplotlib scatter plot legend size

Here we are going to learn how we can set the size of the points in the legend to a fixed. Sometimes we plot scatter graphs with different marker sizes but we want the fixed size of the marker in legend.

Let’s see an example:

Example: Where legend size is not fixed

# Import library


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


x = np.random.randint(10,size=(20))
y1 = np.random.randint(30, size=(20))
y2 = np.random.randint(20, size=(20))
 
# Scatter Plot and define label


plt.scatter(x, y1, s= 50, label='LABEL-1')
plt.scatter(x, y2, s= 150, label='LABEL-2')

# Add legend


plt.legend()

# Display


plt.show()
  • In the above example, we plot a scatter graph by using the plt.scatter() method and we pass s as a parameter to set the size of the to scatter markers.
  • plt.legend() method is used to add a legend to the plot.
matplotlib scatter plot legend size
Not Fixed Size Legend

Here you see that Label 1 marker and Label 2 marker at legend have different sizes.

Example: Where legend size is fixed

# Import library


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



x = np.random.randint(10,size=(20))
y1 = np.random.randint(30, size=(20))
y2 = np.random.randint(20, size=(20))
 
# Scatter Plot and define label


plt.scatter(x, y1, s= 50, label='LABEL-1')
plt.scatter(x, y2, s= 150, label='LABEL-2')

# Add legend fixed size


lgnd = plt.legend(loc="upper right", scatterpoints=1, fontsize=10)
lgnd.legendHandles[0]._sizes = [30]
lgnd.legendHandles[1]._sizes = [30]

# Display


plt.show()

Here we use the plt.legend() method to add a legend to the scatter plot. To set the fixed size of the legend point we use legendHandles[].sizes .

matplotlib scatter plot legend having fixed size
” Scatter Plot having Fixed Size Legend Point”

Read: Horizontal line matplotlib

Python scatter plot legend marker size

Here we are going to learn how to plot scatter graphs with legend marker size.

Let’s see an example:

# Import library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x, y = np.random.rand(2, 30)
color = np.random.randint(1, 40, size=30)
size = np.random.randint(40, 150, size=30)

# Add subplot

fig, ax = plt.subplots()

# Scatter plot

scatter = ax.scatter(x, y, c=color, s=size)

# Add legend

handles, labels = scatter.legend_elements(prop="sizes")
legnd = ax.legend(handles, labels, loc="upper right", title="Sizes")

# Display

plt.show()
  • Here we use the legend_elements() method and pass prop as a parameter and set its value to the size of the marker.
  • And we also use plt.legend() method to add a legend to the plot and we pass handles, labels, loc, title as a parameter.
python scatter plot legend marker size
” Legend Marker Size “

Read: module ‘matplotlib’ has no attribute ‘artist’

Matplotlib scatter plot legend by color

Here we are going to learn how to plot legend by color.

Let’s see an example:

# Import Library


import matplotlib.pyplot as plt
from numpy.random import random

# Define color data


colors = ['b', 'c', 'y', 'm', 'r']

# Plot


data1 = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='Label 1')
data2 = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='Label 2')
data3 = plt.scatter(random(10), random(10), marker='o', color=colors[1],label='Label 3')
data4 = plt.scatter(random(10), random(10), marker='o', color=colors[2],label='Label 4')
data5 = plt.scatter(random(10), random(10), marker='o', color=colors[3],label='Label 5')
data6 = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='Label 6')
data7 = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='Label 7')

# Add legend


plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.08), ncol=3)

# Display


plt.show()
  • In the above example, we use defined color data, and then we use the scatter() method to plot a scatter graph.
  • After this, we use the legend() method to add a legend in the plot and we use bbox_to_anchor() to add legend outside.
matplotlib scatter plot legend by color

Also, check the following article on Python Matplotlib.

In this Python tutorial, we have discussed the “Matplotlib Scatter Plot Legend” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib scatter plot legend
  • Matplotlib scatter plot legend example
  • Matplotlib scatter plot legend position
  • Python scatter plot legend outside
  • Matplotlib scatter plot legend title
  • Matplotlib scatter plot legend facecolor
  • Matplotlib scatter plot show legend
  • Python seaborn scatter plot legend outside
  • Matplotlib scatter plot legend size
  • Python scatter plot legend marker size
  • Matplotlib scatter plot legend by color