{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Customizing legends\n", "\n", "This is a short tutorial showing how different arguments to the `legend` keyword in the **pyam** plotting library affects where the legend is located.\n", "\n", "We use the scenario ensemble from the **first-steps tutorial** ([link](https://github.com/IAMconsortium/pyam/blob/master/docs/tutorials/pyam_first_steps.ipynb))." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pyam import IamDataFrame" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = IamDataFrame(data=\"tutorial_data.csv\").filter(\n", " variable=\"Emissions|CO2\", region=\"World\"\n", ")\n", "\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, a legend will not appear if there are too many entries." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.plot()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By using the `color` argument, we tell the **pyam** plotting library to apply colours by model family.\n", "This reduces the number of legend entries (from 38 model-scenario combinations to 8 model families), and the legend will be shown by default with **matplotlib** standard settings." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.plot(color=\"model\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can use standard **matplotlib** [legend](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.legend.html) arguments by passing a dictionary of keyword arguments." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.plot(color=\"model\", legend=dict(loc=\"center left\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, we also offer support for a few standard special cases, namely legends to the right of a plot and legends below the plot" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pyam.plotting import OUTSIDE_LEGEND" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.plot(color=\"model\", legend=OUTSIDE_LEGEND[\"right\"])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.plot(color=\"model\", legend=OUTSIDE_LEGEND[\"bottom\"])" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.0" } }, "nbformat": 4, "nbformat_minor": 2 }