python - plotly.express - 像 sns.lineplot 中的置信区间

标签 python plotly seaborn plotly-python plotly-express

这是一个带有置信区间的seaborn图示例:

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')

输出

enter image description here

这里尝试在 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

输出:

enter image description here

所以,这与seaborn 的 plotly 相同,但仅适用于其中一种色调。我怎样才能将另一种色调的相同图绘制到同一图上,使其看起来像seaborn?

最佳答案

我花了相当多的时间试图解决这个问题,所以我最终整理了一个小包来做到这一点,使用与seaborn相同的API:https://github.com/MarcoGorelli/bornly

示例:

import bornly as bns

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

enter image description here

关于python - plotly.express - 像 sns.lineplot 中的置信区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70234198/

相关文章:

python - DataLoader worker 意外退出(pid(s) 48817、48818)

c++ - boost python 导出单例

python - 与同一轴嵌套的热图 python dash

python - 共享相同颜色条的绘图堆叠表面

python-3.x - 是否可以使用 seaborn 执行 "zoom inset"?

python - 使用 from_dict() 初始化 pandas DataFrame 的子类

python - python + paramiko 的奇怪内存泄漏

r - 在 plotly R 中更改标题位置

python - 如何调整 seaborn pairplot 中的透明度(alpha)?

python - 设置seaborn/matplotlib始终使用edgecolor ='k'参数