Skip to main content
 首页 » 编程设计

python之将 seaborn lineplot 与分组变量一起使用

2024年11月24日9lvdongjie

我有一个看起来像这样的 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 似乎需要的输入格式非常不同,而且我没有使用 DataFrame 的经验,所以我不知道如何正确转换它。

请您参考如下方法:

我想这就是你想要的:

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) 

输出: