Skip to content
Advertisement

Background with range on seaborn based on two columns

I am trying to add to my several line plots a background that shows a range from value x (column “Min”) to value y (column “Max”) for each year. My dataset looks like that:

JavaScript

I used the following code:

JavaScript

I would like something like this with the range being my “Min” and “Max” by year.

enter image description here

Is it possible to do it? Thank you very much !

Advertisement

Answer

Usually, grid.map is the tool for this, as shown in many examples in the mutli-plot grids tutorial. But you are using relplot to combine lineplot with a FacetGrid as it is suggested in the docs (last example) which lets you use some extra styling parameters.

Because relplot processes the data a bit differently than if you would first initiate a FacetGrid and then map a lineplot (you can check this with grid.data), using grid.map(plt.bar, ...) to plot the ranges is quite cumbersome as it requires editing the grid.data dataframe as well as the x- and y-axis labels.

The simplest way to plot the ranges is to loop through the grid.axes. This can be done with grid.axes_dict.items() which provides the column names (i.e. countries) that you can use to select the appropriate data for the bars (useful if the ranges were to differ, contrary to this example).

The default figure legend does not contain the complete legend including the key for ranges, but the first ax object does so that one displayed instead of the default legend in the following example. Note that I have edited the data you shared so that the min/max ranges make more sense:

JavaScript

relplot

Advertisement