将Seaborn线图与分组变量一起使用

时间:2019-07-12 18:24:05

标签: python pandas dataframe seaborn confidence-interval

我有一个看起来像这样的pandas DataFrame。

      0      1      2     3      4      5     6     7     8     9  Group
0   0.0    0.0    0.0  12.5   12.5    0.0   0.0  12.5   0.0  12.5      1
1   0.0   12.5   12.5  12.5    0.0    0.0   0.0   0.0  12.5  12.5      1
2  37.5   37.5   37.5   0.0   37.5   37.5  25.0  25.0  37.5  25.0      1
3  25.0   50.0   25.0  25.0   50.0   50.0  25.0   0.0  37.5  50.0      1
4  50.0   62.5   50.0  62.5   50.0   50.0  62.5  50.0  62.5  50.0      1
0  12.5   12.5    0.0   0.0   12.5   12.5   0.0   0.0  12.5   0.0      2
1   0.0    0.0   12.5  12.5    0.0   12.5   0.0   0.0  25.0  25.0      2
2  50.0   25.0   37.5  12.5   37.5   25.0  37.5  25.0  37.5  37.5      2
3  25.0   50.0   25.0  12.5   37.5   37.5  25.0   0.0  37.5  50.0      2
4  62.5   50.0   50.0  62.5   50.0   50.0  62.5  50.0  62.5  50.0      2

现在我也想用两行来创建grouped lineplot的seaborn,其中一行基于组1,另一行基于组2。x值应该是行索引(0,1,2, 3,4),y值应为基于DataFrame每行的均值+置信区间。

我的问题是我的数据格式与seaborn的输入要求完全不同,并且我对DataFrames经验不足,所以我不知道如何正确转换它。

1 个答案:

答案 0 :(得分:1)

我想这就是你想要的:

draw_df = df.reset_index().melt(id_vars=['index', 'Group'], var_name='col')

# turn to string
draw_df['Group'] = draw_df.Group.astype(str)

# pass custom palette:
sns.lineplot(x='index', 
             y='value',
             hue='Group', 
             palette=['b','r'],
             data=draw_df)

输出:

enter image description here