Use different y-axes on the left and right of a Matplotlib plot

Python

Matplotlib

Axes

Use multiple y-axes

Luc B.

Python

Matplotlib

If a data analyst wants to compare trends in two datasets, they'll often plot the data in the same chart. However, this approach only works if the datasets are of roughly equivalent magnitudes. If the values in one dataset are ten times the values in the other, plot details in the smaller data are lost.

One technique to address this is using multiple y-axes: the right y-axis is scaled to be appropriate for one dataset, and the left y-axis is scaled for the other.

Code Example

Use the Axes.twinx() function to create a second Axes object that will have tick marks on the right side of the plot.

import matplotlib.pyplot as plt

# Create left and right axes objects
fig, axl = plt.subplots()
axr = axl.twinx()

# Create left side line plot, color accordingly
color = "blue"
axl.plot([1, 2, 3], [1, 2, 3], color=color)
axl.tick_params(axis="y", color=color, labelcolor=color)

# Create right side line plot, color accordingly
color = "red"
axr.plot([1, 2, 3], [90, 80, 70], color=color)
axr.tick_params(axis="y", color=color, labelcolor=color)

plt.show()

png

It's common to color the left and right axes according to their corresponding data, as shown in the plot above. This is done with the Axes.tick_params() function.

More Examples

Pyplot Interface

The example above uses Matplotlib's object oriented interface. The same plot can also be achieved with the pyplot interface using the plt.twinx() function.

import matplotlib.pyplot as plt

# Create left side line plot, color accordingly
color = "blue"
plt.plot([1, 2, 3], [1, 2, 3], color=color)
plt.tick_params(axis="y", color=color, labelcolor=color)

# Create right side line plot, color accordingly
plt.twinx()
color = "red"
plt.plot([1, 2, 3], [90, 80, 70], color=color)
plt.tick_params(axis="y", color=color, labelcolor=color)

plt.show()

png