Joe
Joe

Reputation: 53

How to make Plotly average out observations at a single x-value Python

This is my dataset:

import seaborn as sns
import plotly.graph_objs as go

x = [0,0,0,1,1,1,2,2,2]
y = [1,2,3,4,5,6,7,8,9]

Using:

sns.lineplot(x=x, y=y)

I get following figure: enter image description here

I would like to get the same (at least similar result) in Plotly. Currently I have:

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, 
                         y=y,
                         mode='lines',
                         name='predictions',
                        fill="toself"))

However this is the result I obtain which I am not happy with:

enter image description here

Is it a matter of some specific keyword argument passed to fill? Thanks!

Upvotes: 0

Views: 1015

Answers (1)

rpanai
rpanai

Reputation: 13447

Plotly it's not meant to be a "statistical data visualization library" as seaborn so you should prepare the traces before to plot. For your given example you could do something like

import pandas as pd
import plotly.graph_objs as go

x = [0,0,0,1,1,1,2,2,2]
y = [1,2,3,4,5,6,7,8,9]

df = pd.DataFrame({"x": x, "y": y})

grp = df.groupby("x").agg({"y":{"mean", "min", "max"}})
grp.columns = ["_".join(col) for col in grp.columns]
grp = grp.reset_index()

fig = go.Figure()
fig.add_trace(go.Scatter(x=grp["x"], 
                         y=grp["y_min"],
                         mode='lines',
                         name='y_min',
                         opacity=0.75,
#                          marker = {"color":"lightblue", "width":0.5},
                         line=dict(color='lightblue', width=0.5),
                         showlegend=False
                         ))
fig.add_trace(go.Scatter(x=grp["x"], 
                         y=grp["y_mean"],
                         mode='lines',
                         name='prediction',
                         fill="tonexty",
                         line=dict(color='lightblue', width=2)
                         ))

fig.add_trace(go.Scatter(x=grp["x"], 
                         y=grp["y_max"],
                         mode='lines',
                         name='y_max',
                         opacity=0.75,
                         fill="tonexty",
                         line=dict(color='lightblue', width=0.5),
                         showlegend=False
                         ))

enter image description here

Upvotes: 2

Related Questions