English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matplotlib Dual Axes

It is sometimes useful to have dual x or y axes in a graph. Moreover, when plotting curves with different units. Matplotlib supports this feature through the twinx() and twiny() functions.

In the following example, the plot has dual y-axes, one showing exp(x), and the other showing log(x) -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
#! /usr/bin/env python
 #coding=utf-8
 import matplotlib.pyplot as plt
 import numpy as np
 import math
 plt.rcParams['font.sans-serif'] = ['SimHei']  # Step one (replacement of sans-serif font)
 plt.rcParams['axes.unicode_minus'] = False  # Original source from 【Lidihuo】, commercial redistribution please contact the author for authorization, non-commercial please retain the original link:
 fig = plt.figure()
 a1 = fig.add_axes([0,0,1,1])
 x = np.arange(1,11)
 a1.plot(x, np.exp(x))
 a1.set_ylabel('exp')
 a2 = a1.twinx()
 a2.plot(x, np.log(x),'ro-')
 a2.set_ylabel('log')
 fig.legend(labels=('exp','log'),loc='upper left')
 plt.show()

Execute the above example code to get the following result -