Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.secondary_xaxis() function in axes module of matplotlib library is also used to add a second x-axis to this axes.
Syntax: Axes.secondary_xaxis(self, location, *, functions=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
- location : This parameter is the position to put the secondary axis.
- functions : This parameter is used to specify the transform function and its inverse.
Returns: This method returns the following:
- ax : This return the axes._secondary_axes.SecondaryAxis.
Note: This function works in Matplotlib version >= 3.1
Below examples illustrate the matplotlib.axes.Axes.secondary_xaxis() function in matplotlib.axes:
Example 1:
Python3
# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.plot([ 1 , 2 , 3 ]) ax.set_xlabel( 'X-Axis' ) ax.set_ylabel( 'Y-Axis' ) secax = ax.secondary_xaxis( 'top' ) secax.set_xlabel( 'Secondary-X-Axis' ) ax.set_title( 'matplotlib.axes.Axes.secondary_xaxis() Example' , fontsize = 14 , fontweight = 'bold' ) plt.show() |
Output:
Example 2:
Python3
# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np import datetime import matplotlib.dates as mdates from matplotlib.transforms import Transform from matplotlib.ticker import ( AutoLocator, AutoMinorLocator) fig, ax = plt.subplots(constrained_layout = True ) x = np.arange( 0 , 500 , 2 ) y = np.sin( 3 * x * np.pi / 180 ) ax.plot(x, y) ax.set_xlabel( 'Degree' ) ax.set_ylabel( 'Frequency' ) def val1(x): return x * np.pi / 180 def val2(x): return x * 180 / np.pi secax = ax.secondary_xaxis( 'top' , functions = (val1, val2)) secax.set_xlabel( 'Radian' ) ax.set_title( 'matplotlib.axes.Axes.secondary_xaxis() Example' , fontsize = 14 , fontweight = 'bold' ) plt.show() |
Output: