{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Plots with different scales\n\nTwo plots on the same Axes with different left and right scales.\n\nThe trick is to use *two different Axes* that share the same *x* axis.\nYou can use separate `matplotlib.ticker` formatters and locators as\ndesired since the two Axes are independent.\n\nSuch Axes are generated by calling the `.Axes.twinx` method. Likewise,\n`.Axes.twiny` is available to generate Axes that share a *y* axis but\nhave different top and bottom scales.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n# Create some mock data\nt = np.arange(0.01, 10.0, 0.01)\ndata1 = np.exp(t)\ndata2 = np.sin(2 * np.pi * t)\n\nfig, ax1 = plt.subplots()\n\ncolor = 'tab:red'\nax1.set_xlabel('time (s)')\nax1.set_ylabel('exp', color=color)\nax1.plot(t, data1, color=color)\nax1.tick_params(axis='y', labelcolor=color)\n\nax2 = ax1.twinx() # instantiate a second Axes that shares the same x-axis\n\ncolor = 'tab:blue'\nax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1\nax2.plot(t, data2, color=color)\nax2.tick_params(axis='y', labelcolor=color)\n\nfig.tight_layout() # otherwise the right y-label is slightly clipped\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.axes.Axes.twinx` / `matplotlib.pyplot.twinx`\n - `matplotlib.axes.Axes.twiny` / `matplotlib.pyplot.twiny`\n - `matplotlib.axes.Axes.tick_params` / `matplotlib.pyplot.tick_params`\n\n.. tags::\n\n component: axes\n plot-type: line\n level: beginner\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }