Scatter Plot
Python · Data Visualization
Theory
A scatter plot draws one dot per record, with one numeric variable on the x-axis and another on the y-axis, so you can see whether they move together. Dots rising from left to right mean a positive relationship, falling means negative, and a shapeless cloud means little relationship. Points far from the rest are outliers.
ax.scatter(x, y) can encode more variables: c= colours each dot by a value or category (with cmap= and fig.colorbar for numbers), s= sets dot size, and alpha=0.5 makes overlapping dots visible. The strength of a straight-line relationship is the correlation coefficient r from np.corrcoef, between -1 and 1, and np.polyfit(x, y, 1) gives the slope and intercept of a trend line you can draw with ax.plot. Correlation alone does not prove that one variable causes the other.
Why we use it
Before modelling, you need to know how two variables relate. A scatter plot shows the direction, strength and shape of the relationship and exposes outliers and clusters that summary numbers miss.
When to use it
Use a scatter plot for two numeric variables measured on the same records, such as experience vs salary or ad spend vs sales. For a variable over time use a line plot; with many thousands of points use alpha, smaller dots or a 2-D histogram.
How it works
- Two numeric columns from the same records
- ax.scatter(x, y) places one dot per record
- Another variable to show? Yes: Encode it with c= (colour) or s= (size). No: Keep plain dots.
- Look for direction, strength, clusters and outliers
- Optionally add a trend line with np.polyfit
- Relationship understood before modelling
Syntax
ax.scatter(x, y, c=values, s=sizes, alpha=0.7, cmap='viridis')
fig.colorbar(sc, ax=ax)
np.corrcoef(x, y)[0, 1]
slope, intercept = np.polyfit(x, y, 1)Example
fig, ax = plt.subplots()
ax.scatter([1, 3, 5, 7], [4.0, 6.0, 9.0, 11.5])
ax.set_xlabel('Experience (years)')Key points
- Each dot is one record: x and y are two numeric columns
- c= and s= add a third and fourth variable via colour and size
- alpha= reveals overlapping points
- np.corrcoef gives r from -1 to 1 for straight-line strength
- Correlation is not causation