{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Twin Axes with delta_zorder\n\n`~matplotlib.axes.Axes.twinx` and `~matplotlib.axes.Axes.twiny` accept a\n*delta_zorder* keyword argument (a relative offset added to the original Axes'\nzorder) that controls whether the twin Axes is drawn in front of or behind the\noriginal Axes.\n\nMatplotlib also automatically manages background patch visibility for twinned\nAxes groups so that only the bottom-most Axes has a visible background patch\n(respecting ``frameon``). This avoids the background of a higher-zorder twin\nAxes covering artists drawn on the underlying Axes.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(0, 10, 400)\ny_main = np.sin(x)\ny_twin = 0.4 * np.cos(x) + 0.6\n\nfig, ax = plt.subplots()\n\n# Put the twin Axes behind the original Axes (relative to the original zorder).\nax2 = ax.twinx(delta_zorder=-1)\n\n# Draw something broad on the twin Axes so that the stacking is obvious.\nax2.fill_between(x, 0, y_twin, color=\"C1\", alpha=0.35, label=\"twin fill\")\nax2.plot(x, y_twin, color=\"C1\", lw=6, alpha=0.8)\n\n# Draw overlapping artists on the main Axes; they appear on top.\nax.scatter(x[::8], y_main[::8], s=35, color=\"C0\", edgecolor=\"k\", linewidth=0.5,\n zorder=3, label=\"main scatter\")\nax.plot(x, y_main, color=\"C0\", lw=4)\n\nax.set_xlabel(\"x\")\nax.set_ylabel(\"main y\")\nax2.set_ylabel(\"twin y\")\nax.set_title(\"Twin Axes drawn behind the main Axes using delta_zorder\")\n\nfig.tight_layout()\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.12.15" } }, "nbformat": 4, "nbformat_minor": 0 }