plt.scatter() plots one point per observation, showing the relationship between two numeric variables — the go-to chart for spotting correlation or clusters.
A Basic Scatter Plot
R Code
height = [150, 160, 165, 170, 180] weight = [50, 55, 60, 65, 75] plt.scatter(height, weight, color="steelblue") plt.title("Height vs Weight") plt.xlabel("Height (cm)") plt.ylabel("Weight (kg)") plt.show()
Colouring Points by Group
R Code
gender = ["M","F","M","F","M"] colours = ["blue" if g == "M" else "deeppink" for g in gender] plt.scatter(height, weight, c=colours) plt.show()
Adding a Trend Line
R Code
import numpy as np coeffs = np.polyfit(height, weight, 1) # fit a straight line (degree 1) trend = np.poly1d(coeffs) plt.scatter(height, weight, color="steelblue") plt.plot(height, trend(height), color="red") plt.show()
Advanced: Bubble Chart (Size as a Third Variable)
🚀 Advanced Example
Mapping a third numeric variable to point size turns a scatter plot into a bubble chart.R Code
age = [20, 25, 30, 35, 40] plt.scatter(height, weight, s=[a*5 for a in age], alpha=0.6, color="steelblue") plt.title("Bubble size represents age") plt.show()
Key Points
- plt.scatter(x, y) plots two numeric variables as points.
- Map a grouping variable to c= (colour) to distinguish categories.
- np.polyfit(x, y, 1) fits a straight trend line to overlay with plt.plot().
- Mapping a third variable to s= (size) creates a bubble chart.