Scatter plot
- Machine Learning course
- Beginner
- Lesson 104/112
- 5 min
A scatter plot shows the relationship between two variables with points.
Scatter plot
A scatter plot shows the relationship of two numeric variables with points. With the c parameter, points are coloured by class; in classification you immediately see whether the classes separate:
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
fig, ax = plt.subplots()
sc = ax.scatter(X[:, 2], X[:, 3], c=y, cmap="viridis", s=20)
ax.set_xlabel("taç yaprak uzunluğu")
ax.set_ylabel("taç yaprak genişliği")
fig.colorbar(sc)In Iris these two features separate the three species almost completely; this explains why the tree found them important.
Truth versus prediction
The clearest way to evaluate a regression model is to plot the true values against the predictions. In a good model the points gather around the y = x diagonal:
ax.scatter(y_test, p, alpha=0.6)
lim = [y_test.min(), y_test.max()]
ax.plot(lim, lim, "r--") # perfect-prediction lineIf the points pile up below the diagonal, the model is systematically under-predicting.
Practice Plot the classes
Draw columns 3 and 4 of Iris (X[:, 2], X[:, 3]) as a scatter plot with c=y and save it. Then compute each class's mean petal length with [X[y == k, 2].mean() for k in range(3)] and print it with np.round(..., 2).
Starter code
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
# buraya yazSample solution
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
fig, ax = plt.subplots()
ax.scatter(X[:, 2], X[:, 3], c=y)
fig.savefig("iris.png")
print(np.round([X[y == k, 2].mean() for k in range(3)], 2))Expected output
[1.46 4.26 5.55]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which parameter colours the points by class label?
- s
- alpha
- marker
- c Correct answer
Explanation: c takes the colour values; s sets the size and alpha the transparency.
2 Draw the points semi-transparent.
ax.scatter(x, y, ____=0.5)
ax.scatter(x, y, alpha=0.5)
Explanation: alpha is between 0 (invisible) and 1 (opaque); it reveals overlapping points.
3 Match the parameters.
| Term | Meaning |
|---|---|
c |
Colour values |
s |
Point size |
alpha |
Transparency |
cmap |
Colour map |