0
votes

First time posting here. I have been recently been introduced to seaborn and plotly python libraries. They produce some great plots.

I have been struggling recreating a seaborn plot in plotly. I have a dataframe that looks like this example: Example data set

In seaborn if I use the following code:

sns.catplot(data=test, x='time', y='y', hue='group', kind='point')

I get a great graph in which the groups have automatically been averaged and plots two lines with error bars. I have two lines on my graph of group 'a' and 'b' showing the average value over each timepoint: Seaborn example graph

If I try to replicate this in plotly using:

px.line(test,x='time', y='y', color='group')

I get the individual lines for each group (three for 'a' and three for 'b') like this:plotly example

Is there way to plot the averages in plotly, rather than the individual points. I can not figure out how to get plotly to plot the averages of each group like seaborn does.

Any help would be greatly appreciated.

Hope this makes sense.

Thanks

1

1 Answers

2
votes

With plotly you need to use transformations, in this case several, one to group them and then one to create the averages (with aggregate).

For instance, with some data:

import numpy as np
import pandas as pd

# some data
N=24
ds = pd.DataFrame({'group': np.random.choice(['a','b'],N),
                   'time': np.random.randint(0,6,N),
                   'y': np.random.randint(1,15,N)})
ds.sort_values(by=['group', 'time'],inplace=True)

then you can use plotly:

import plotly.io as pio

data = [dict(
  type = 'scatter', x = ds.time, y = ds.y,
  mode = 'lines+markers',
  transforms = [
      dict(
        type = 'groupby',
        groups = ds.group),
      dict(
        type = 'aggregate',
        groups = ds.time,
        aggregations = [dict(target = 'y', func = 'avg')]),
    ]
)]

fig_dict = dict(data=data)
pio.show(fig_dict, validate=False)