matplotlib.axes.Axes.twiny() in Python

• Last Updated : 21 Apr, 2020

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.

matplotlib.axes.Axes.twiny() Function

The Axes.twiny() function in axes module of matplotlib library is used to create a twin Axes sharing the yaxis.

Syntax: Axes.twiny(self)

Return value: This method is used to returns the following.

• ax_twin : This returns the newly created Axes instance.

Below examples illustrate the matplotlib.axes.Axes.twiny() function in matplotlib.axes:

Example 1:

 `# Implementation of matplotlib function``# Implementation of matplotlib function``import` `matplotlib.pyplot as plt``import` `numpy as np``  ` `  ` `def` `GFG1(temp):``    ``return` `(``5.` `/` `9.``) ``*` `(temp ``-` `32``)``  ` `def` `GFG2(ax1):``    ``y1, y2 ``=` `ax1.get_ylim()``    ``ax_twin .set_ylim(GFG1(y1), GFG1(y2))``    ``ax_twin .figure.canvas.draw()``  ` `fig, ax1 ``=` `plt.subplots()``ax_twin ``=` `ax1.twiny()``  ` `ax1.callbacks.connect(``"ylim_changed"``, GFG2)``ax1.plot(np.linspace(``-``40``, ``120``, ``100``))``ax1.set_ylim(``0``, ``100``)``  ` `ax1.set_xlabel(``'Fahrenheit'``)``ax_twin .set_xlabel(``'Celsius'``)`` ` `fig.suptitle('matplotlib.axes.Axes.twiny()\`` ``function Example\n\n', fontweight ``=``"bold"``)``plt.show()`

Output:

Example 2:

 `# Implementation of matplotlib function``import` `numpy as np``import` `matplotlib.pyplot as plt`` ` `# Create some mock data``t ``=` `np.arange(``0.01``, ``10.0``, ``0.001``)``data1 ``=` `np.exp(t)``data2 ``=` `np.sin(``0.4` `*` `np.pi ``*` `t)`` ` `fig, ax1 ``=` `plt.subplots()`` ` `color ``=` `'tab:blue'``ax1.set_ylabel(``'time (s)'``)``ax1.set_xlabel(``'exp'``, color ``=` `color)``ax1.plot(data1, t, color ``=` `color)``ax1.tick_params(axis ``=``'x'``, labelcolor ``=` `color)`` ` `ax2 ``=` `ax1.twiny()`` ` `color ``=` `'tab:green'``ax2.set_xlabel(``'sin'``, color ``=` `color)``ax2.plot(data2, t, color ``=` `color)``ax2.tick_params(axis ``=``'x'``, labelcolor ``=` `color)`` ` `fig.suptitle('matplotlib.axes.Axes.twiny()\`` ``function Example\n\n', fontweight ``=``"bold"``)``plt.show()`

Output:

My Personal Notes arrow_drop_up