How to plot a figure with two different axes in matplotlib ?

Published: April 18, 2023

Updated: April 19, 2023

Tags: Python; Matplotlib;

DMCA.com Protection Status

Adding a secondary x or y axis in matplotlib can be done in several ways. Examples:

Using twinx() or twiny() methods

Suppose we have a histogram created from randomly generated numbers that follow a gamma distribution. We aim to include a secondary y-axis to display the cumulative density function.

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)

shape = 3.0
scale = 1.0

nb_random_points = 10000

data = np.random.gamma(shape, scale, nb_random_points)

plt.hist(data,bins=40)

plt.title('How to plot a figure with two different axes in matplotlib ? ')

plt.savefig('plot_a_figure_with_two_different_axes_in_matplotlib_01.png')

plt.show()

Output

How to plot a figure with two different axes in matplotlib ?
How to plot a figure with two different axes in matplotlib ?

Now we can add a secondary y-axis by using the twinx() method:

ax2 = ax.twinx()

which create another plot with a shared x-axis. Illustration

from scipy.stats import gamma

import numpy as np

np.random.seed(42)

shape = 3.0
scale = 1.0

nb_random_points = 10000

data = np.random.gamma(shape, scale, nb_random_points)

fig, ax1 = plt.subplots()

ax1.hist(data,bins=40)

ax1.set_ylabel('Counts')

ax2 = ax1.twinx()

X = np.linspace(0,16,100)

CDF = gamma.cdf(X, shape, 0, scale)

ax2.plot(X,CDF,color='coral')

ax2.set_ylabel('CDF', color='coral')
ax2.tick_params(axis='y', labelcolor='coral')

plt.grid()

fig.tight_layout()

plt.title('How to plot a figure with two different axes in matplotlib ? ')

plt.savefig('plot_a_figure_with_two_different_axes_in_matplotlib_02.png')

plt.show()

Output

How to plot a figure with two different axes in matplotlib ?
How to plot a figure with two different axes in matplotlib ?

Using secondary_xaxis() or secondary_yaxis()

Another approach is to use secondary_yaxis(), Example:

import matplotlib.pyplot as plt
import numpy as np

heights = np.linspace(0,100,100) # Pounds
weights = np.exp( heights * 0.04 ) # inches

fig, ax = plt.subplots()

ax.plot(heights,weights)
ax.set_xlabel('heights (inches)')
ax.set_ylabel('Weight (Pounds)')

def convert_pound_to_kilogram(weights):
    return 0.453592 * weights


def convert_kilogram_to_pound(weights):
    return weights / 0.453592


secax_y2 = ax.secondary_yaxis('right', functions=(convert_pound_to_kilogram, convert_kilogram_to_pound))

secax_y2.set_ylabel('Weight (Kilograms)')

ax.grid()

plt.title('How to plot a figure with two different axes in matplotlib ? ')

plt.savefig('plot_a_figure_with_two_different_axes_in_matplotlib_03.png')

plt.show()

Output

How to plot a figure with two different axes in matplotlib ?
How to plot a figure with two different axes in matplotlib ?

References

Links Site
matplotlib.axes.Axes.secondary_xaxis matplotlib.org
Secondary Axis matplotlib.org
Plots with different scales matplotlib.org
Image

of