Norman
Norman

Reputation: 310

Python: Setting Seaborn lineplot error band edge color

I am using Seaborn to make lineplots with a band indicating standard deviations. Something just like the second/third plot in the doc below: https://seaborn.pydata.org/generated/seaborn.lineplot.html?highlight=lineplot#seaborn.lineplot

I am wondering is that possible to set the edgecolor for the error band separately? I can change linestyle of the band through err_kws. But, if I pass "edgecolor" through err_kws, it seems that nothing happens. Is there someway to allow me to get control with the edges?

Thanks!

Upvotes: 3

Views: 3976

Answers (2)

Bonlenfum
Bonlenfum

Reputation: 20175

As djakubosky notes, the color of the line and the error band are coupled together internally in seaborn's lineplot. I suggest that it is cleaner to modify the properties of the artists after the plot has been generated. This is a cleaner alternative than editing the library source code directly (maintenance headaches, etc).

For the example data shown on the sns.lineplot docs, we can update the error band properties as follows:

import seaborn as sns
fmri = sns.load_dataset("fmri")
ax = sns.lineplot(x="timepoint", y="signal", data=fmri)

# by inspection we see that the PolyCollection is the first artist
for child in ax.get_children():
    print(type(child))

# and so we can update its properties
ax.get_children()[0].set_color('k')
ax.get_children()[0].set_hatch('//')

polycollection properties modified

It may be more robust to select by property of the artist rather than selecting the first artist (especially if you have already rendered something on the same axes), e.g. along these lines:

from matplotlib.collections import PolyCollection
for child in ax.findobj(PolyCollection):
    child.set_color('k')
    child.set_hatch('//')

Upvotes: 3

djakubosky
djakubosky

Reputation: 1007

It appears that it isn't really possible to change this color under the current seaborn implementation. This is because they pass the color of the main line explicitly to the error band as ax.fillbetweenx(... color=original_color). After playing around in the past, I found that this color arg seems to supersede the other color arguments such as facecolor and edgecolor, thus it doesn't matter what you put in there in the err_kws. However you could fix it by editing line 810 in site-packages/seaborn/relational.py from:

ax.fill_between(x, low, high, color=line_color, **err_kws)

to

ax.fill_between(x, low, high, **err_kws)

and passing the colors explicitly through err_kws.

Upvotes: 1

Related Questions