twinx() (Matplotlib)

ax.twinx() creates a second y-axis that shares the same x-axis, so you can plot two series with different units or scales on one chart. ax.twiny() does the mirror image for a shared y-axis.

Matplotlib

Sometimes two related series live on incompatible scales — temperature and rainfall, price and volume. twinx() returns a new Axes overlaid on the original, sharing its x-axis but with an independent y-axis on the right side, so each series uses its own scale while lining up in time.

You plot the first series on the original Axes and the second on the twin: ax2 = ax.twinx(); ax2.plot(...). Color-code each y-axis and its labels to match its data, because a dual-axis chart is easy to misread when it isn't clear which axis a line belongs to.

Use it sparingly. Twin axes can imply a correlation that the unrelated scales don't justify, so many visualization guides suggest two stacked panels instead when clarity matters more than compactness.

Syntax

ax2 = ax.twinx()  |  ax2 = ax.twiny()

Examples

Python — ax2 shares ax's x-axis but has its own y-axis.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax2 = ax.twinx()
print(type(ax2).__name__)

Output:

Axes

Learn it in a lesson

See also

Back to the Dictionary