Open In App

How to add a legend to a scatter plot in Matplotlib ?

Last Updated : 31 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Adding a legend to a scatter plot in Matplotlib means providing clear labels that describe what each group of points represents. For example, if your scatter plot shows two datasets, adding a legend will display labels for each dataset, helping viewers interpret the plot correctly. We will explore simple and effective ways to add legends to scatter plots using Matplotlib.

Using label parameter

This is the most straightforward and preferred way to add a legend. You assign labels directly when creating each scatter plot, making your code clean, readable and scalable. Just call plt.legend() once at the end to display them.

Python
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 6)
y1 = x**2
y2 = x**3

plt.scatter(x, y1, label="x²")
plt.scatter(x, y2, label="x³")

plt.legend()
plt.show()

Output

legend-using-label
Using label parameter

Explanation: We generate x values from 1 to 5 using np.arange(1, 6) and compute y as and. Using plt.scatter(), we plot both with labels. plt.legend() then displays "x²" and "x³" beside their respective points.

Using loc

When the default legend position gets in the way, you can control where it appears using loc, and even spread it across multiple columns using ncol. It gives you more layout flexibility and keeps your plot tidy.

Python
import matplotlib.pyplot as plt
import numpy as np

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

plt.scatter(x, y1, label="x*2")
plt.scatter(x, y2, label="x*3")

plt.legend(loc="lower right", ncol=2)
plt.show()

Output

legend-custom-location
Using loc

Explanation: We define x as a list from 1 to 5 and compute y1 as x*2 and y2 as x*3. Using plt.scatter(), we plot both with labels. plt.legend() is used with loc="lower right" and ncol=2 to position the legend neatly at the bottom right in two columns.

Using legend()

If you didn’t label your plots when creating them, you can manually pass a list of legend labels to plt.legend(). It's quick but less maintainable, especially with many plots.

Python
import matplotlib.pyplot as plt
import numpy as np

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

plt.legend(["x*2", "x*3"])
plt.show()

Output

legend-manual-labels
Using legend()

Explanation: We plot y1 and y2 against x using plt.scatter() without setting labels directly. Instead, we pass a list of labels ["x*2", "x*3"] to plt.legend() to manually assign names in the legend.

Related articles:


Next Article

Similar Reads