Customizing legendsΒΆ

This is a short tutorial showing how different arguments to the legend keyword in the pyam plotting library affects where the legend is located.

We use the scenario ensemble from the first-steps tutorial (link).

[1]:
from pyam import IamDataFrame
[2]:
df = IamDataFrame(data="tutorial_data.csv").filter(
    variable="Emissions|CO2", region="World"
)

df.head()
[INFO] 12:12:08 - pyam.core: Reading file tutorial_data.csv
/home/docs/checkouts/readthedocs.org/user_builds/pyam-iamc/checkouts/stable/pyam/utils.py:318: FutureWarning: The previous implementation of stack is deprecated and will be removed in a future version of pandas. See the What's New notes for pandas 2.1.0 for details. Specify future_stack=True to adopt the new implementation and silence this warning.
  .stack(dropna=True)
[2]:
model scenario region variable unit year value
0 AIM/CGE 2.1 CD-LINKS_INDCi World Emissions|CO2 Mt CO2/yr 2010 33954.0254
1 AIM/CGE 2.1 CD-LINKS_INDCi World Emissions|CO2 Mt CO2/yr 2020 39274.5709
2 AIM/CGE 2.1 CD-LINKS_INDCi World Emissions|CO2 Mt CO2/yr 2030 36068.4425
3 AIM/CGE 2.1 CD-LINKS_INDCi World Emissions|CO2 Mt CO2/yr 2040 38447.2877
4 AIM/CGE 2.1 CD-LINKS_INDCi World Emissions|CO2 Mt CO2/yr 2050 39519.9596

By default, a legend will not appear if there are too many entries.

[3]:
df.plot()
[INFO] 12:12:08 - pyam.plotting: >=13 labels, not applying legend
[3]:
<Axes: title={'center': 'region: World - variable: Emissions|CO2'}, xlabel='Year', ylabel='Mt CO2/yr'>
../_images/tutorials_legends_4_2.png

By using the color argument, we tell the pyam plotting library to apply colours by model family. 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.

[4]:
df.plot(color="model")
[4]:
<Axes: title={'center': 'region: World - variable: Emissions|CO2'}, xlabel='Year', ylabel='Mt CO2/yr'>
../_images/tutorials_legends_6_1.png

You can use standard matplotlib legend arguments by passing a dictionary of keyword arguments.

[5]:
df.plot(color="model", legend=dict(loc="center left"))
[5]:
<Axes: title={'center': 'region: World - variable: Emissions|CO2'}, xlabel='Year', ylabel='Mt CO2/yr'>
../_images/tutorials_legends_8_1.png

However, we also offer support for a few standard special cases, namely legends to the right of a plot and legends below the plot

[6]:
from pyam.plotting import OUTSIDE_LEGEND
[7]:
df.plot(color="model", legend=OUTSIDE_LEGEND["right"])
[7]:
<Axes: title={'center': 'region: World - variable: Emissions|CO2'}, xlabel='Year', ylabel='Mt CO2/yr'>
../_images/tutorials_legends_11_1.png
[8]:
df.plot(color="model", legend=OUTSIDE_LEGEND["bottom"])
[8]:
<Axes: title={'center': 'region: World - variable: Emissions|CO2'}, xlabel='Year', ylabel='Mt CO2/yr'>
../_images/tutorials_legends_12_1.png