DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How to Add Legends to Matplotlib Scatter Plots

Use labeled scatter collections for discrete groups, or generate legend handles for numeric color and size mappings with PathCollection.legend_elements().
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For separate categories, draw one scatter collection per category, assign each a label, then call ax.legend(). For values encoded by a single scatter plot’s colors or marker sizes, use that collection’s legend_elements() method and pass its handles and labels to the legend.

Choose the legend method that matches your scatter plot

Matplotlib legends describe plotted artists. The simplest approach depends on whether your markers represent distinct groups or numeric values mapped to color or size.

What the markers represent Recommended approach
Discrete groups, each with its own plotted collection Use one scatter() call per group, set a descriptive label, then call ax.legend().
Numeric values mapped to color in one collection Keep the collection returned by scatter(); use legend_elements(prop="colors").
Numeric values mapped to marker size in one collection Keep the collection returned by scatter(); use legend_elements(prop="sizes").
Both color and size encode values Create separate, titled legends from the same collection, preserving the first legend with ax.add_artist().

Matplotlib’s stable scatter-with-legend gallery documents the separate-collection pattern. The examples and API references cited here are from Matplotlib’s stable documentation accessed October 4, 2026; the gallery, collections API, and figure API identify version 3.11.2, while the pyplot legend reference identifies 3.11.1. Stable documentation may change, so check the API if you are targeting a materially older release. Matplotlib scatter plot with a legend · Matplotlib collections API · Matplotlib pyplot legend reference.

Add a legend for discrete groups

Use a separate scatter collection for each group and give it a meaningful label. Matplotlib’s gallery recommends creating one scatter plot per item that should appear in the legend and setting its label accordingly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
fig, ax = plt.subplots()
for group, color in groups:
    ax.scatter(group.x, group.y, color=color, label=group.name)

ax.legend(title="Group")

Here, groups represents your own iterable of group data and colors; group.name becomes the legend text. A title such as “Group” clarifies what the entries identify.

Make a legend for color values

If one scatter collection maps numeric values to color, retain the object returned by ax.scatter(). Its legend_elements() method returns matching legend handles and labels.

points = ax.scatter(x, y, c=values)
handles, labels = points.legend_elements(prop="colors")
ax.legend(handles, labels, title="Value")

For more control over generated entries or their appearance, legend_elements() accepts options such as num and fmt; a formatter can also shape the labels. These options help when you want to limit the entries or make their numeric text easier to read. See the collections API for the method’s parameters.

Make a legend for marker sizes

For numeric values mapped to marker area, request size entries with prop="sizes":

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
points = ax.scatter(x, y, s=sizes)
handles, labels = points.legend_elements(prop="sizes")
ax.legend(handles, labels, title="Size")

If the sizes you passed to scatter() were calculated from another quantity, the generated labels otherwise describe the size mapping rather than necessarily showing that original quantity. Pass func as the inverse of your size transformation when the legend should display the original values. For example, if your plotting values were produced by multiplying the original values by a factor, the inverse divides by that factor:

factor = 4
points = ax.scatter(x, y, s=original_values * factor)
handles, labels = points.legend_elements(
    prop="sizes",
    func=lambda plotted_sizes: plotted_sizes / factor,
)
ax.legend(handles, labels, title="Original value")

Choose an inverse that matches the transformation actually used to compute the plotted sizes.

Explain color and size with two legends

When both color and size carry information, generate a legend for each encoding and give each a clear title. Matplotlib replaces an Axes’ existing legend when another is created, so add the first legend back as an artist before creating the second.

points = ax.scatter(x, y, c=classes, s=sizes)

color_legend = ax.legend(
    *points.legend_elements(prop="colors"),
    title="Class",
    loc="upper left",
)
ax.add_artist(color_legend)

size_handles, size_labels = points.legend_elements(prop="sizes", alpha=0.6)
ax.legend(size_handles, size_labels, title="Size", loc="lower right")

The distinct positions keep the two explanations separate; adjust them if either legend obscures points or important plot details. Matplotlib’s scatter legend gallery demonstrates this two-legend sequence.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Position a legend and fix an empty one

Use loc to select a standard position. Use bbox_to_anchor when you need to control the anchor point or position a legend relative to the Axes or Figure. The available placement behavior is documented in the figure API.

If ax.legend() produces no entries, check that the plotted artists have labels. Automatic legend discovery excludes labels beginning with an underscore, which is also the default label behavior; without labeled artists, the legend is empty. Set a label when creating the artist or later with set_label().

When automatic discovery is not suitable, pass handles and labels explicitly:

ax.legend(handles, labels)

Keep the two sequences in the same order: the label at each position is associated with the handle at that position. Matplotlib’s pyplot legend reference discourages supplying labels alone for existing artists, since relying on implicit order can associate text with the wrong plotted item.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an authoritative reference on labels, handles, placement, and legend arguments, see the pyplot legend documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.