首页 > 解决方案 > 如何向 seaborn FacetGrid 添加额外的图并指定颜色

问题描述

有没有办法创建一个 Seaborn 线图,所有线都是灰色的,平均值为红线?我正在尝试这样做,relplot但我不知道如何将平均值与数据分开(看起来平均值没有被绘制?)。

制作可重现的数据框

np.random.seed(1)
n1 = 100
n2 = 10
idx = np.arange(0,n1*2)
x, y, cat, id2 = [], [], [], []

x1 = list(np.random.uniform(-10,10,n2))
for i in idx: 
    x.extend(x1)
    y.extend(list(np.random.normal(loc=0, scale=0.5, size=n2)))
    cat.extend(['A', 'B'][i > n1])
    id2.append(idx[i])

id2 = id2 * n2
id2.sort()
df1 = pd.DataFrame(list(zip(id2, x, y, cat)), 
                  columns =['id2', 'x', 'y', 'cat']
                 )

绘图尝试

g = sns.relplot(
    data=df1, x='x', y='y', hue='id2',
    col='cat', kind='line',
    palette='Greys',
    facet_kws=dict(sharey=False, 
                   sharex=False
                  ),
    legend=False
)

在此处输入图像描述

标签: pythonseabornlinear-regression

解决方案


我想你想units在调用中relplot添加一层lineplotusing map

import seaborn as sns
import pandas as pd

fm = sns.load_dataset('fmri').query("event == 'stim'")
g = sns.relplot(
    data=fm, kind='line',
    col='region', x='timepoint', y='signal', units='subject',
    estimator=None, color='.7'
)
g.data = fm  # Hack needed to work around bug on v0.11, fixed in v0.12.dev
g.map(sns.lineplot, 'timepoint', 'signal', color='r', ci=None, lw=3)

在此处输入图像描述


推荐阅读