{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Multiple y-axis with Spines\n\nCreate multiple y axes with a shared x-axis. This is done by creating\na `~.axes.Axes.twinx` Axes, turning all spines but the right one invisible\nand offset its position using `~.spines.Spine.set_position`.\n\nNote that this approach uses `matplotlib.axes.Axes` and their\n`~matplotlib.spines.Spine`\\s. Alternative approaches using non-standard Axes\nare shown in the :doc:`/gallery/axisartist/demo_parasite_axes` and\n:doc:`/gallery/axisartist/demo_parasite_axes2` examples.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nfig.subplots_adjust(right=0.75)\n\ntwin1 = ax.twinx()\ntwin2 = ax.twinx()\n\n# Offset the right spine of twin2. The ticks and label have already been\n# placed on the right by twinx above.\ntwin2.spines.right.set_position((\"axes\", 1.2))\n\np1, = ax.plot([0, 1, 2], [0, 1, 2], \"C0\", label=\"Density\")\np2, = twin1.plot([0, 1, 2], [0, 3, 2], \"C1\", label=\"Temperature\")\np3, = twin2.plot([0, 1, 2], [50, 30, 15], \"C2\", label=\"Velocity\")\n\nax.set(xlim=(0, 2), ylim=(0, 2), xlabel=\"Distance\", ylabel=\"Density\")\ntwin1.set(ylim=(0, 4), ylabel=\"Temperature\")\ntwin2.set(ylim=(1, 65), ylabel=\"Velocity\")\n\nax.yaxis.label.set_color(p1.get_color())\ntwin1.yaxis.label.set_color(p2.get_color())\ntwin2.yaxis.label.set_color(p3.get_color())\n\nax.tick_params(axis='y', colors=p1.get_color())\ntwin1.tick_params(axis='y', colors=p2.get_color())\ntwin2.tick_params(axis='y', colors=p3.get_color())\n\nax.legend(handles=[p1, p2, p3])\n\nplt.show()" ] } ], "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 }