New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

Matplotlib Twin Axes

In this tutorial, we will cover the concept of twin/dual axes in matplotlib.

In the axes class, there are many figure elements present like Axis, Tick, Line2D, Text, Polygon, etc., which are used to set the coordinate system.

When we say twin axes, it means a figure can have dual x or y-axes. Also, when plotting curves with different units together, then also twin axes is very useful.

In Matplotlib this task is supported with the twinx and twiny functions.

Matplotlib twinx() and twiny() Function

In the Axes Module, there is a function named Axes.twinx() function which is used to create a twin Axes that are sharing the x-axis. Similarly, the function twiny() is used to create a second x axis in your figure, which means twin axes sharing the y-axis.

The syntax to use this function is as follows:

# for x axis
Axes.twinx(self)
# for y axis
Axes.twiny(self)

Note: This function does not take any parameters, if you will do so then it will raise errors.

The values returned by this method are as follows:

ax_twin: which indicates that it will return the newly created Axes instance.

Now it's time to dive into some examples using this function,

Example 1:

Here is an example of twin axes plot in matplotlib:

import numpy as np 
import matplotlib.pyplot as plt 

t = np.arange(0.01, 10.0, 0.001) 
data1 = np.exp(t) 
data2 = np.cos(0.4 * np.pi * t) 

fig, ax1 = plt.subplots() 

color = 'tab:orange'
ax1.set_xlabel('time (s)') 
ax1.set_ylabel('exp', color = color) 
ax1.plot(t, data1, color = color) 
ax1.tick_params(axis ='y', labelcolor = color) 

ax2 = ax1.twinx() 

color = 'tab:cyan'
ax2.set_ylabel('cos', color = color) 
ax2.plot(t, data2, color = color) 
ax2.tick_params(axis ='y', labelcolor = color) 

fig.suptitle('matplotlib.axes.Axes.twinx()function Example\n\n', fontweight ="bold") 

plt.show() 

The output for the above code is as follows:

twin axes matplotlib example

In the above code, we used the twinx() function and we got twin axes sharing the x-axis.

Summary:

The twinx() and twiny() functions are used when you want to show multiple scale for the data in a figure or if you want to have multiple plots in a single figure.