plotly.express - confidence intervals like in sns.lineplot

Viewed 425

Here's an example of a seaborn plot, which comes with confidence intervals:

import plotly.express as px
import seaborn as sns
import pandas as pd
import numpy as np

np.random.seed(1)
df = pd.DataFrame({'x': np.tile(np.arange(5), 6), 'y': np.random.randn(30), 'hue': np.repeat(['foo', 'bar'], [15, 15])})

sns.lineplot(data=df, x='x', y='y', hue='hue')

which outputs

enter image description here

Here's an attempt to do the same in plotly:

group = ['hue', 'x']
err = df.groupby(group)['y'].std() / np.sqrt(df.groupby(group)['y'].size())
pdf = df.groupby(group)['y'].mean().reset_index()
pdf['2'] = pdf['y'] + 1.96*pdf.set_index(group).index.map(err)
pdf['1'] = pdf['y'] - 1.96*pdf.set_index(group).index.map(err)
pdf['0'] = pdf['y']
pdf = pdf.drop('y', axis=1)
pdf = pd.melt(pdf, id_vars=['x', 'hue'])
pdf = pdf.sort_values(['x', 'variable', 'hue'], ascending = True)

fig = px.line(
    pdf[pdf['hue']=='foo'],
    line_group='hue', 
    x = 'x',
    y = 'value',
    color='variable',
    color_discrete_map = {'0': 'blue', '1': 'blue', '2': 'blue'}
)

fig.update_traces(name = 'interval', selector = dict(name = '2'), showlegend=False)
fig.update_traces(fill = 'tonexty')
fig.update_traces(fillcolor = 'rgba(0,0,0,0)', selector = dict(name = '0'))
fig.update_traces(fillcolor = 'rgba(0,0,0,0)', line_color = 'rgba(0, 0, 255, 0.5)',
                  showlegend = False, selector = dict(name = '1'))

fig

which outputs:

enter image description here

So, that's the same as the seaborn plot, but for just one of the hues. How can I also get the same plot for the other hue onto the same plot, so it looks like the seaborn one?

1 Answers

I spent considerable time trying to solve this, so I ended up putting together a little package to do this, with same API as seaborn's: https://github.com/MarcoGorelli/bornly

Example:

import bornly as bns

fmri = bns.load_dataset("fmri")
bns.lineplot(data=fmri, x="timepoint", y="signal", hue="event")

enter image description here

Related