typestar

Two scales on one plot in Python

twinx shares the x axis and gives the second series its own y.

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]
tpm = [88, 92, 99, 104, 110]
accuracy = [96.0, 97.2, 97.8, 98.4, 98.1]

figure, left = plt.subplots()
right = left.twinx()

left.plot(days, tpm, color="#7c5cff", marker="o")
right.plot(days, accuracy, color="#e06c75", linestyle="--")

left.set_ylabel("tpm", color="#7c5cff")
right.set_ylabel("accuracy %", color="#e06c75")
right.set_ylim(95, 100)
figure.savefig("twin.png")

How it works

  1. Use it when the units genuinely differ, not to cram plots together.
  2. Color the tick labels to match their series.
  3. Two legends, or one combined from both handle lists.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
470
Tokens
156
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 2 of 4 in Reading the plot, step 11 of 14 in Plotting with matplotlib.

← Previous Next →