Matplotlib Scatter Plots
Visualize relationships between variables with scatter plots, color maps, and bubble sizes.
Basic Scatter Plot
fig, ax = plt.subplots()
ax.scatter(x, y, color="teal", alpha=0.7)
ax.set_xlabel("Feature A")
ax.set_ylabel("Feature B")Scatter plots reveal correlation patterns, clusters, and outliers.
Color Encoding
Map a third dimension to color using the c parameter.
scatter = ax.scatter(x, y, c=z, cmap="viridis")
fig.colorbar(scatter, ax=ax, label="Intensity")Colorbars provide context for continuous color scales.
Bubble Charts
Encode magnitude with marker size using the s parameter (area in points^2).
ax.scatter(x, y, s=volume * 200, alpha=0.5, edgecolor="white")Scale size values to maintain visual balance across the chart.
Categorical Classes
Plot categories with discrete colors and legend entries.
for label, color in {"A": "#2563eb", "B": "#f97316"}.items():
mask = df["segment"] == label
ax.scatter(df.loc[mask, "x"], df.loc[mask, "y"], label=label, color=color)
ax.legend(title="Segment")Standardize color assignments and share updates via info.studygrid@gmail.com.
Transparency and Overplotting
Use alpha to handle dense data. Consider hexbin or density plots for extremely large datasets.
Next Steps
Transition to bar charts to communicate categorical comparisons and totals.
Color and Size by Data
A scatter plot can encode extra variables through point color (c) and size (s).
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 1000 * np.random.rand(50)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap="viridis")
plt.colorbar() # legend for the color scale
plt.show()Try It Yourself
Exercise: Make a scatter plot of study hours vs score for 5 students.
Show solution
import matplotlib.pyplot as plt
hours = [1, 2, 3, 4, 5]
scores = [52, 60, 68, 77, 90]
plt.scatter(hours, scores)
plt.xlabel("hours"); plt.ylabel("score")
plt.show()Key Takeaways
- Scatter plots reveal relationships and clusters between two variables.
- Encode more data with color (
c) and size (s). - Add
colorbar()to explain a color scale.
📘 Real-World Deep Dive
Knowing <strong>Matplotlib Scatter (Matplotlib)</strong> well is what turns Matplotlib from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Matplotlib Scatter that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50); y = np.random.rand(50)
plt.scatter(x, y, c=y, cmap="viridis"); plt.colorbar()
plt.show()Expected Output
(no output)Common mistakes
- Calling
plt.plotwithoutplt.show()in scripts (orplt.savefig) produces no visible output. - Passing mismatched array shapes to
plt.plot(x, y)raises a uselessValueError— verify shapes withx.shapeandy.shapefirst. - Mixing
numpy.float64withpandas.Seriesis OK, but mixingnumpy.datetime64with Pythondatetime.dateneeds an explicit cast. - Treating Matplotlib Scatter as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- For large scatter plots use
plt.scatter(..., s=1, rasterised=True)or switch todatashader. - Use the
aggbackend on web services:import matplotlib; matplotlib.use("Agg"). - Plot once and reuse the figure: avoid embedding Matplotlib into tight Python loops without an explicit
clear(). - When working with Matplotlib, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.