Scatter Plots in Matplotlib

Make a scatter plot with plt.scatter(), then color points by category or value, change their size, and add legends and trend lines.

To make a scatter plot in Matplotlib, call plt.scatter(x, y), or ax.scatter(x, y) on an axes. s sets the point size, c or color the color, alpha the transparency, and marker the symbol.

Quick Example

The sample data is a set of used cars with their age, price, mileage, and fuel type.

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

rng = np.random.default_rng(8)
n = 180
age = rng.uniform(0.5, 12, n)
fuel = rng.choice(["Gasoline", "Hybrid", "Electric"], n, p=[0.5, 0.3, 0.2])
base = pd.Series(fuel).map({"Gasoline": 27, "Hybrid": 31, "Electric": 37}).to_numpy()
cars = pd.DataFrame({
    "age": age,
    "price": base * np.exp(-0.11 * age) * rng.lognormal(0, 0.12, n),
    "mileage": np.clip(age * rng.normal(11, 2.5, n), 1, None),
    "fuel": fuel,
})

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
ax.scatter(cars["age"], cars["price"], s=40, alpha=0.7, color="#3d5a80")
ax.set_xlabel("Age (years)")
ax.set_ylabel("Price ($ thousands)")
ax.set_title("Used car prices (sample data)")
plt.show()

Scatter plot of used car price against age, with price falling as cars get older

plt.scatter() with lists

The two arguments can be lists, NumPy arrays, or pandas columns, as long as they're the same length:

plt.figure(figsize=(8, 5), layout="constrained")
plt.scatter([1, 2, 3, 4, 5], [12, 19, 15, 25, 31], s=120, color="#ee6c4d")
plt.xlabel("x")
plt.ylabel("y")
plt.show()

Five large orange points on a simple scatter plot

With a DataFrame, you can pass column names along with data=: ax.scatter("age", "price", data=cars).

Color points by category

Call scatter() once per group, with a label for the legend:

colors = {"Gasoline": "#8d99ae", "Hybrid": "#2a9d8f", "Electric": "#e76f51"}

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
for name, color in colors.items():
    group = cars[cars["fuel"] == name]
    ax.scatter(group["age"], group["price"], s=40, alpha=0.8,
               color=color, label=name)

ax.set_xlabel("Age (years)")
ax.set_ylabel("Price ($ thousands)")
ax.legend(title="Fuel")
plt.show()

Scatter plot of price against age colored by fuel type, with electric cars generally priced above hybrid and gasoline cars of the same age

Don't pass the text column to c=: ax.scatter(x, y, c=cars["fuel"]) raises a ValueError, because c expects colors or numbers. In Seaborn, sns.scatterplot(data=cars, x="age", y="price", hue="fuel") does the grouping for you.

Color points by value with a colorbar

Pass a numeric column to c, choose a cmap, and hand the result to fig.colorbar():

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
points = ax.scatter(cars["age"], cars["price"], c=cars["mileage"],
                    cmap="viridis_r", s=40)
fig.colorbar(points, ax=ax, label="Mileage (thousands)")
ax.set_xlabel("Age (years)")
ax.set_ylabel("Price ($ thousands)")
plt.show()

Scatter plot of price against age with points shaded by mileage, darker for older high-mileage cars

vmin and vmax fix the ends of the color scale, which keeps colors comparable between charts. See Matplotlib colormaps for the available names and colorbar customization for placement and ticks.

Change the point size

s is the marker area in points squared. The default is 36 (6 points across), so doubling a point's width takes four times the s. Pass an array to size points by a variable, and use legend_elements() to explain the sizes:

sizes = cars["mileage"] * 2

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
points = ax.scatter(cars["age"], cars["price"], s=sizes, alpha=0.5,
                    color="#6a4c93", edgecolors="white")
handles, labels = points.legend_elements(
    prop="sizes", num=4, color="#6a4c93", alpha=0.5,
    func=lambda s: s / 2,  # convert marker area back to mileage
)
ax.legend(handles, labels, title="Mileage (k)", labelspacing=1.2, borderpad=1)
ax.set_xlabel("Age (years)")
ax.set_ylabel("Price ($ thousands)")
plt.show()

Bubble scatter plot with larger circles for higher mileage and a legend showing the size scale

Fix overlapping points with alpha or hexbin

With thousands of points, a scatter plot turns into a solid blob. Make the markers small and transparent, or count points in hexagonal bins with ax.hexbin() (see hexbin plots and 2D histograms):

x = rng.normal(0, 1, 20_000)
y = 0.6 * x + rng.normal(0, 0.8, 20_000)

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(11, 3.8), sharey=True,
                                    layout="constrained")
ax1.scatter(x, y)
ax1.set_title("Default")
ax2.scatter(x, y, s=4, alpha=0.1, linewidths=0)
ax2.set_title("s=4, alpha=0.1")
bins = ax3.hexbin(x, y, gridsize=35, cmap="Blues", mincnt=1)
ax3.set_title("hexbin")
fig.colorbar(bins, ax=ax3, label="Points")
plt.show()

Three views of 20,000 points: solid default markers hide the density, small transparent markers and a hexbin plot show a dense center

Change the marker shape

marker accepts codes such as "o" (circle), "s" (square), "^" (triangle), "D" (diamond), and "x". One scatter() call takes one marker, so loop over groups to vary it. Using shape as well as color helps readers who can't tell the colors apart.

markers = {"Gasoline": "o", "Hybrid": "s", "Electric": "^"}

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
for name, marker in markers.items():
    group = cars[cars["fuel"] == name]
    ax.scatter(group["age"], group["price"], marker=marker, s=45,
               facecolors="none", edgecolors=colors[name],
               linewidths=1.5, label=name)

ax.set_xlabel("Age (years)")
ax.set_ylabel("Price ($ thousands)")
ax.legend()
plt.show()

Scatter plot with hollow circles, squares, and triangles for the three fuel types

The marker reference lists every shape.

Add a trend line

Fit a line with np.polyfit() and draw it with ax.plot(). Car prices fall by a percentage each year, so this fits a straight line to the log of price, which becomes a curve on the original scale:

slope, intercept = np.polyfit(cars["age"], np.log(cars["price"]), 1)
x_fit = np.linspace(cars["age"].min(), cars["age"].max(), 100)

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
ax.scatter(cars["age"], cars["price"], s=35, alpha=0.5, color="#3d5a80")
ax.plot(x_fit, np.exp(intercept + slope * x_fit), color="#d62828",
        linewidth=2.5, label=f"{1 - np.exp(slope):.0%} lower per year")
ax.legend()
ax.set_xlabel("Age (years)")
ax.set_ylabel("Price ($ thousands)")
plt.show()

Scatter plot of price against age with a fitted red curve showing about 11 percent lower price per year

For a straight line, skip the log and use intercept + slope * x_fit. Seaborn's regplot and lmplot add the fit and a confidence band automatically.

plt.scatter vs plt.plot for points

scatter(x, y) plot(x, y, "o")
Size and color per point Yes (s, c) No, one style per call
Colormap and colorbar Yes No
Size argument s (area, points²) markersize (width, points)
Speed with very large data Slower Faster

To label individual points, see annotating data points. For a third axis, try a 3D scatter plot.

Similar Topics