MATPLOTLIB:Line and scatter plots
Mastering line and scatter plots concepts and implementation.
Lines are for order, points are for pairs
Use a line when the horizontal axis has an order you must not break: time, a sequence, a sorted measurement. Use a scatter plot when each row is an independent pair and connecting them would invent a path that is not in the data.
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
temp = [18.2, 19.0, 21.5, 20.1, 22.4]
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(days, temp, marker="o", color="#6b21a8")
ax.set_title("Temperature across five days")
ax.set_xlabel("Day")
ax.set_ylabel("Celsius")
fig.tight_layout()
marker="o" draws a point at each measurement so a flat segment is still visible. color accepts a hex code.
Scatter
Penguin bill length and bill depth are a pair per bird. A line through them would depend on row order in the file, which is meaningless. Scatter does not connect the points.
import matplotlib.pyplot as plt
import pandas as pd
penguins = pd.read_csv("penguins.csv").dropna(
subset=["bill_length_mm", "bill_depth_mm"]
)
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(
penguins["bill_length_mm"],
penguins["bill_depth_mm"],
s=18,
alpha=0.75,
c="#3b82f6",
)
ax.set_xlabel("Bill length (mm)")
ax.set_ylabel("Bill depth (mm)")
ax.set_title("Penguin bills")
fig.tight_layout()
s is the marker area. alpha lets overlapping points show through. Drop missing measurements before plotting, or Matplotlib will omit them with a warning you then have to explain.
Two series
Call plot or scatter twice on the same axes, and give each call a label. Then ax.legend().
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 2, 3], label="steady")
ax.plot([1, 2, 3], [1, 2, 4], label="faster")
ax.legend()
ax.set_title("Two lines, one panel")
What to notice
- If you are unsure, ask whether swapping two rows should change the picture. If yes, you wanted a line. If no, you wanted points.
ax.plot(y)uses0, 1, 2, ...as the horizontal axis. Passxexplicitly when the positions are not that sequence.- Set labels after the drawing calls. They describe the axes, not a single series.
Try this
Plot bill length against body mass for the penguins file as a scatter plot. Label both axes with the units.
Next: bars, histograms, and box plots.