How to Make a Bubble Chart in Matplotlib

Build a bubble chart with ax.scatter, scale bubble areas correctly, color by group, add a size legend and label the points.

To make a bubble chart in Matplotlib, call ax.scatter(x, y, s=sizes), where s is the area of each marker in points squared. Scale your third variable to that area, and add transparency with alpha so overlapping bubbles stay visible. This post uses Matplotlib 3.11.

Quick Example

Fifteen made-up cities: monthly rent, average commute, population (bubble size) and region (color).

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

cities = pd.DataFrame({
    "city": ["Alder", "Brook", "Cedar", "Dune", "Elm", "Fern", "Glen",
             "Harbor", "Iris", "Juniper", "Kestrel", "Linden", "Moss",
             "North", "Orchard"],
    "rent": [1450, 2100, 1250, 1750, 2650, 1100, 1600, 2900, 1350, 1950,
             2300, 1500, 980, 2450, 1850],
    "commute": [24, 33, 19, 27, 41, 17, 31, 38, 22, 25, 36, 29, 21, 28, 34],
    "population": [0.4, 2.1, 0.3, 0.9, 5.8, 0.2, 1.1, 4.2, 0.5, 1.4, 2.7,
                   0.8, 0.15, 1.9, 1.2],                        # millions
    "region": ["North", "Coast", "North", "South", "Coast", "North", "South",
               "Coast", "North", "South", "Coast", "South", "North", "Coast",
               "South"],
})
colors = {"North": "#4c72b0", "Coast": "#dd8452", "South": "#55a868"}
scale = 350                         # points² of area per million people

fig, ax = plt.subplots(figsize=(8.5, 5.5))
for region, group in cities.groupby("region"):
    ax.scatter(group.rent, group.commute, s=group.population * scale,
               color=colors[region], alpha=0.65, edgecolor="white",
               label=region)

ax.set_xlabel("Median monthly rent ($)")
ax.set_ylabel("Average commute (minutes)")
ax.set_title("Bigger cities cost more and take longer to cross")
ax.margins(0.12)
legend = ax.legend(title="Region", loc="upper left")
for handle in legend.legend_handles:      # same size for every legend dot
    handle.set_sizes([80])
plt.show()

Bubble chart of rent against commute time for 15 cities, with bubble area showing population and color showing region; the largest cities sit toward the upper right

How should I scale bubble sizes?

Make area proportional to the value. Passing the value squared, or scaling the radius, makes large values look far bigger than they are.

values = np.array([1, 2, 4])

fig, axes = plt.subplots(1, 2, figsize=(8, 2.8))
for ax, sizes, title in [
        (axes[0], values * 800, "Area ∝ value (correct)"),
        (axes[1], values ** 2 * 400, "Radius ∝ value (exaggerates)")]:
    ax.scatter([0, 1, 2], [0, 0, 0], s=sizes, color="#8172b3")
    for i, v in enumerate(values):
        ax.text(i, -0.75, str(v), ha="center", fontsize=12)
    ax.set_title(title)
    ax.set_xlim(-0.6, 2.7)
    ax.set_ylim(-1, 0.8)
    ax.axis("off")
plt.show()

Two rows of three circles for the values 1, 2 and 4: scaling area looks proportional, scaling radius makes the circle for 4 look enormous

On the right, the circle for 4 has 16 times the area of the circle for 1.

Because s is in points, bubbles keep the same size on screen when you change the axis limits. Pick scale so the largest bubble is readable without hiding its neighbors.

Add a bubble size legend

legend_elements(prop="sizes") on the object returned by scatter() builds legend entries. func converts marker area back into your data units. Draw all points in one call so one object knows the whole size range.

fig, ax = plt.subplots(figsize=(8.5, 5.5))
points = ax.scatter(cities.rent, cities.commute,
                    s=cities.population * scale,
                    c=cities.region.map(colors), alpha=0.65,
                    edgecolor="white")

handles, labels = points.legend_elements(
    prop="sizes", num=[0.5, 2, 5], func=lambda s: s / scale,
    fmt="{x:g} million", color="gray", alpha=0.6)
size_legend = ax.legend(handles, labels, title="Population",
                        loc="upper left", labelspacing=1.8, borderpad=1.2,
                        handletextpad=1.5)
ax.add_artist(size_legend)

# A second legend for the colors
region_handles = [plt.Line2D([], [], ls="", marker="o", markersize=9,
                             color=c, label=r) for r, c in colors.items()]
ax.legend(handles=region_handles, title="Region", loc="lower right")

ax.set_xlabel("Median monthly rent ($)")
ax.set_ylabel("Average commute (minutes)")
ax.margins(0.12)
plt.show()

Bubble chart with a population size legend in the upper left and a region color legend in the lower right

ax.add_artist() keeps the first legend when ax.legend() creates the second.

Label the bubbles

Label only the points worth naming. Draw bubbles from largest to smallest so small ones end up on top.

ordered = cities.sort_values("population", ascending=False)

fig, ax = plt.subplots(figsize=(8.5, 5.5))
ax.scatter(ordered.rent, ordered.commute, s=ordered.population * scale,
           c=ordered.region.map(colors), alpha=0.65, edgecolor="white")
for row in ordered.head(3).itertuples():
    ax.annotate(f"{row.city}\n{row.population:g}M", (row.rent, row.commute),
                ha="center", va="center", fontsize=9, fontweight="bold")
ax.set_xlabel("Median monthly rent ($)")
ax.set_ylabel("Average commute (minutes)")
ax.margins(0.12)
plt.show()

Bubble chart with names and populations written on the three largest cities

Use color for a fourth number

Pass a numeric column to c with a cmap, and add a colorbar. Here the color is a made-up livability score.

rng = np.random.default_rng(193)
cities["score"] = (88 - 0.8 * cities.commute
                   + rng.normal(0, 5, len(cities))).round()

fig, ax = plt.subplots(figsize=(8.5, 5.2))
points = ax.scatter(cities.rent, cities.commute,
                    s=cities.population * scale, c=cities.score,
                    cmap="viridis", alpha=0.8, edgecolor="black", lw=0.5)
fig.colorbar(points, ax=ax, label="Livability score")
ax.set_xlabel("Median monthly rent ($)")
ax.set_ylabel("Average commute (minutes)")
ax.margins(0.12)
plt.show()

Bubble chart colored by livability score with a colorbar, with darker bubbles at longer commutes

Practical tips

  • Readers judge area poorly. Use size for the least important variable, and label values that matter.
  • Start sizes from zero: a value of 0 should have no area. Don't rescale to a minimum-to-maximum range.
  • Negative values can't be sizes. Use color for them.
  • For hover labels, use Plotly's animated bubble charts or px.scatter(size=...).

Similar Topics