{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Different scales on the same Axes\n\nDemo of how to display two scales on the left and right y-axis.\n\nThis example uses the Fahrenheit and Celsius scales.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef fahrenheit2celsius(temp):\n \"\"\"\n Returns temperature in Celsius given Fahrenheit temperature.\n \"\"\"\n return (5. / 9.) * (temp - 32)\n\n\ndef make_plot():\n\n # Define a closure function to register as a callback\n def convert_ax_c_to_celsius(ax_f):\n \"\"\"\n Update second axis according to first axis.\n \"\"\"\n y1, y2 = ax_f.get_ylim()\n ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2))\n ax_c.figure.canvas.draw()\n\n fig, ax_f = plt.subplots()\n ax_c = ax_f.twinx()\n\n # automatically update ylim of ax2 when ylim of ax1 changes.\n ax_f.callbacks.connect(\"ylim_changed\", convert_ax_c_to_celsius)\n ax_f.plot(np.linspace(-40, 120, 100))\n ax_f.set_xlim(0, 100)\n\n ax_f.set_title('Two scales: Fahrenheit and Celsius')\n ax_f.set_ylabel('Fahrenheit')\n ax_c.set_ylabel('Celsius')\n\n plt.show()\n\nmake_plot()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. 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 }