ML Scatter Plot
A scatter plot maps two variables onto x and y axes as individual points, making it the fastest way to spot whether - and how strongly - they are correlated.
What Is a Scatter Plot?
A scatter plot displays each observation as a single point positioned according to two numeric variables - one on the x-axis, one on the y-axis. Unlike a histogram, which shows the distribution of one variable, a scatter plot reveals the relationship between two variables at a glance: whether they move together, move oppositely, or show no clear pattern at all.
Creating a Scatter Plot with Matplotlib
Matplotlib's scatter() function plots paired x and y arrays as dots. It's often the very first chart drawn before fitting any regression model, because it tells you whether a straight line - or any model at all - is a reasonable fit for the data.
Example
import matplotlib.pyplot as plt
# Car age (years) vs. resale value (in $1000s)
age = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
value = [28, 25, 23, 20, 18, 15, 13, 11, 9, 7]
plt.scatter(age, value)
plt.title("Car Age vs. Resale Value")
plt.xlabel("Age (years)")
plt.ylabel("Value ($1000s)")
plt.show()Spotting Correlation Visually
Correlation describes how tightly two variables move together. If points trend upward from left to right, the variables have a positive correlation; if points trend downward, the correlation is negative; if points are scattered with no visible pattern, there is little to no correlation. The tighter the points cluster around an imaginary line, the stronger the correlation.
Example
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
x = np.random.normal(50, 10, 100)
# Strong positive correlation: y closely tracks x plus a little noise
y_strong = x * 1.2 + np.random.normal(0, 5, 100)
# Weak/no correlation: y is independent random noise
y_weak = np.random.normal(50, 10, 100)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].scatter(x, y_strong)
axes[0].set_title("Strong Correlation")
axes[1].scatter(x, y_weak)
axes[1].set_title("No Correlation")
plt.show()- Upward-sloping cluster of points = positive correlation.
- Downward-sloping cluster of points = negative correlation.
- Points scattered with no visible trend = little or no correlation.
- Tightly packed points around a line = strong correlation; widely spread points = weak correlation.
- A curved (non-straight) pattern hints that a linear model is the wrong tool - consider polynomial regression instead.
Example
import numpy as np
import matplotlib.pyplot as plt
# Study hours vs. exam score for 15 students
hours = np.array([1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8])
score = np.array([52, 55, 58, 60, 63, 65, 70, 72, 75, 78, 80, 83, 85, 88, 91])
plt.scatter(hours, score, color="darkorange")
plt.title("Study Hours vs. Exam Score")
plt.xlabel("Hours Studied")
plt.ylabel("Exam Score")
plt.grid(True)
plt.show()Exercise: ML Scatter Plot
What does a scatter plot primarily help reveal between two variables?