{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Secondary Axis\n\nSometimes we want a secondary axis on a plot, for instance to convert\nradians to degrees on the same plot. We can do this by making a child\naxes with only one axis visible via `.axes.Axes.secondary_xaxis` and\n`.axes.Axes.secondary_yaxis`. This secondary axis can have a different scale\nthan the main axis by providing both a forward and an inverse conversion\nfunction in a tuple to the *functions* keyword argument:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import datetime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.dates as mdates\n\nfig, ax = plt.subplots(layout='constrained')\nx = np.arange(0, 360, 1)\ny = np.sin(2 * x * np.pi / 180)\nax.plot(x, y)\nax.set_xlabel('angle [degrees]')\nax.set_ylabel('signal')\nax.set_title('Sine wave')\n\n\ndef deg2rad(x):\n return x * np.pi / 180\n\n\ndef rad2deg(x):\n return x * 180 / np.pi\n\n\nsecax = ax.secondary_xaxis('top', functions=(deg2rad, rad2deg))\nsecax.set_xlabel('angle [rad]')\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, the secondary axis is drawn in the Axes coordinate space.\nWe can also provide a custom transform to place it in a different\ncoordinate space. Here we put the axis at Y = 0 in data coordinates.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, ax = plt.subplots(layout='constrained')\nx = np.arange(0, 10)\nnp.random.seed(19680801)\ny = np.random.randn(len(x))\nax.plot(x, y)\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_title('Random data')\n\n# Pass ax.transData as a transform to place the axis relative to our data\nsecax = ax.secondary_xaxis(0, transform=ax.transData)\nsecax.set_xlabel('Axis at Y = 0')\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is the case of converting from wavenumber to wavelength in a\nlog-log scale.\n\n
In this case, the xscale of the parent is logarithmic, so the child is\n made logarithmic as well.
In order to properly handle the data margins, the mapping functions\n (``forward`` and ``inverse`` in this example) need to be defined beyond the\n nominal plot limits. This condition can be enforced by extending the\n interpolation beyond the plotted values, both to the left and the right,\n see ``x1n`` and ``x2n`` below.