TExcelTAD
Home › Matplotlib › Multiple Axes (twinx)

Multiple Axes (twinx)

Sometimes two measurements share an x axis but have completely different units, like temperature in °C and rainfall in mm per month. Matplotlib can give one plot a second y axis on the right with ax.twinx() (or a second x axis on top with ax.twiny()). It can also add secondary axes that show the same quantity in another unit.

twinx(): a second y axis

ax.twinx() creates a new Axes that shares the x axis with ax but has its own y axis on the right:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
temp = [5, 6, 9, 12, 16, 19, 22, 22, 18, 14, 9, 6]
rain = [80, 60, 55, 45, 50, 40, 30, 35, 55, 85, 95, 90]

fig, ax1 = plt.subplots(figsize=(7, 4), layout="constrained")
ax1.bar(months, rain, color="C0", alpha=0.6)
ax1.set_ylabel("Rainfall (mm)", color="C0")
ax1.tick_params(axis="y", colors="C0")

ax2 = ax1.twinx()
ax2.plot(months, temp, color="C3", marker="o", lw=2)
ax2.set_ylabel("Temperature (°C)", color="C3")
ax2.tick_params(axis="y", colors="C3")
ax1.set_title("Climate chart")
plt.show()

print("Axes in figure:", len(fig.axes))
print("Shared x limits:", ax1.get_xlim() == ax2.get_xlim())
Axes in figure: 2
Shared x limits: True

Colouring each y axis like its series is essential: otherwise the reader cannot tell which scale belongs to which data.

A combined legend

Each Axes has its own legend, so labels from both need to be collected manually:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

week = np.arange(1, 13)
visitors = np.array([1.2, 1.5, 1.4, 1.9, 2.4, 2.2, 2.8, 3.1, 3.0, 3.6, 4.1, 4.4])   # thousands
conversion = np.array([2.1, 2.3, 2.2, 2.0, 1.8, 1.9, 1.7, 1.6, 1.7, 1.5, 1.4, 1.4]) # percent

fig, ax1 = plt.subplots(figsize=(7, 4), layout="constrained")
l1 = ax1.plot(week, visitors, color="C0", label="Visitors (k)")
ax1.set(xlabel="Week", ylabel="Visitors (thousands)")

ax2 = ax1.twinx()
l2 = ax2.plot(week, conversion, color="C1", linestyle="--", label="Conversion (%)")
ax2.set_ylabel("Conversion rate (%)")

lines = l1 + l2
ax1.legend(lines, [line.get_label() for line in lines], loc="upper center")
plt.show()

orders = visitors * 1000 * conversion / 100
print("Orders per week:", np.round(orders).astype(int).tolist())
Orders per week: [25, 34, 31, 38, 43, 42, 48, 50, 51, 54, 57, 62]

Be careful with dual axes

Two independent y axes can be misleading: by choosing the two ranges you can make any two series appear to move together, cross, or diverge. The same data from above tells a different story with other limits:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

week = np.arange(1, 13)
visitors = np.array([1.2, 1.5, 1.4, 1.9, 2.4, 2.2, 2.8, 3.1, 3.0, 3.6, 4.1, 4.4])
conversion = np.array([2.1, 2.3, 2.2, 2.0, 1.8, 1.9, 1.7, 1.6, 1.7, 1.5, 1.4, 1.4])

fig, (ax_a, ax_b) = plt.subplots(2, 1, figsize=(7, 5), sharex=True, layout="constrained")
ax_a.plot(week, visitors, color="C0")
ax_a.set_ylabel("Visitors (k)")
ax_a.set_title("Small multiples: one scale per panel, no ambiguity")
ax_b.plot(week, conversion, color="C1")
ax_b.set_ylabel("Conversion (%)")
ax_b.set_xlabel("Week")
plt.show()

change_v = visitors[-1] / visitors[0] - 1
change_c = conversion[-1] / conversion[0] - 1
print(f"Visitors {change_v:+.0%}, conversion {change_c:+.0%}")
Visitors +267%, conversion -33%

Two stacked panels with a shared x axis ("small multiples") are often the clearer choice. Use twinx when the reader really needs both series in one place, and always label and colour both axes.

Secondary axes for unit conversion

When the second axis shows the same quantity in a different unit, use secondary_xaxis/secondary_yaxis. You give a pair of functions converting there and back, and Matplotlib keeps the two scales consistent:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

def c_to_f(c):
    return c * 9 / 5 + 32

def f_to_c(f):
    return (f - 32) * 5 / 9

hour = np.arange(0, 24)
temp_c = 12 + 8 * np.sin((hour - 9) / 24 * 2 * np.pi)

fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.plot(hour, temp_c, color="C3")
ax.set(xlabel="Hour", ylabel="Temperature (°C)")
sec = ax.secondary_yaxis("right", functions=(c_to_f, f_to_c))
sec.set_ylabel("Temperature (°F)")
plt.show()

print(f"Max: {temp_c.max():.1f} °C = {c_to_f(temp_c.max()):.1f} °F")
Max: 20.0 °C = 68.0 °F
Tool Second axis shows Data drawn on it
ax.twinx() / ax.twiny() a different quantity yes, it's a full Axes
ax.secondary_yaxis(loc, functions=...) the same quantity in another unit no, it only adds ticks

Test yourself

What does ax2 = ax.twinx() create?

  1. A copy of the plot
  2. A new Axes sharing the x axis, with its own y axis on the right
  3. A second figure
  4. A secondary x axis on top

Why do lines from ax2 not appear in ax.legend()?

  1. Twin axes can't have labels
  2. Each Axes only collects its own labelled artists
  3. Legends only work with bars
  4. You must call plt.show() first

Which tool fits a right-hand axis showing °F for the same °C data?

  1. ax.twinx()
  2. ax.secondary_yaxis("right", functions=(c_to_f, f_to_c))
  3. plt.subplot(1, 2, 2)
  4. ax.set_yscale("fahrenheit")