如何在单个x值Python上进行Plotly平均出观测值

问题描述 投票:0回答:1

这是我的数据集:

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]

使用中:

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

我得到下图:enter image description here

我希望在Plotly中获得相同(至少相似的结果)。目前我有:

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

但是这是我获得的结果,对此我感到不满意:

enter image description here

这与传递来填充的某些特定关键字参数有关吗?谢谢!

python plotly seaborn
1个回答
0
投票

通常,这并不意味着它是一个“统计数据可视化库”,因此您应该在绘制之前准备好迹线。对于给定的示例,您可以执行以下操作:

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

© www.soinside.com 2019 - 2024. All rights reserved.