如何在seaborn python中组合两个relplots? [英] How to combine two relplots in seaborn python?

查看:80
本文介绍了如何在seaborn python中组合两个relplots?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 sns.relplot 在单个图中绘制数据框的两个数据列.数据框如下所示:

index x-axis col1 col2 group group20 0 27 26 交流电1 1 45 27 B D2 2 48 22 交流电3 3 35 24 B D4 4 49 38 交流电5 5 46 29 B D6 6 29 37 交流7 7 38 41 B D8 8 24 46 交流9 9 46 38 B D10 10 37 23 交流

在这里,我想针对 x 轴数据绘制 col1 和 col2.'group' 是 'hue' 的值,'group2' 是 relplot 中的 'col' 的值.

我可以使用两个单独的 relplots 分别绘制两列.

col1 的绘图

col2 的绘图

我想合并这两个图,以便有一个包含 col1 和 col2 的图.

解决方案

您可以

I would like to plot two data columns of a dataframe in a single plot using sns.relplot. The dataframe looks like this:

index   x-axis  col1    col2    group   group2
0   0   27  26  A   C
1   1   45  27  B   D
2   2   48  22  A   C
3   3   35  24  B   D
4   4   49  38  A   C
5   5   46  29  B   D
6   6   29  37  A   C
7   7   38  41  B   D
8   8   24  46  A   C
9   9   46  38  B   D
10  10  37  23  A   C

Here, I want to plot col1 and col2 together against x-axis data. 'group' is the value of 'hue', and 'group2' for 'col' in the relplot.

I am able to plot the two columns separately using two individual relplots.

Plot of col1

Plot of col2

I would like to combine the two plots such that there is one single plot containing col1 and col2.

解决方案

You can melt your DataFrame and use the resulting variable as a style grouping:

from io import StringIO
import numpy as np
import pandas as pd
import seaborn as sns

data = """index   x-axis  col1    col2    group   group2
0   0   27  26  A   C
1   1   45  27  B   D
2   2   48  22  A   C
3   3   35  24  B   D
4   4   49  38  A   C
5   5   46  29  B   D
6   6   29  37  A   C
7   7   38  41  B   D
8   8   24  46  A   C
9   9   46  38  B   D
10  10  37  23  A   C"""

df = pd.read_csv(StringIO(data), index_col=[0], sep=" ", skipinitialspace=True)

sns.relplot(
    data=df.melt(id_vars=["x-axis", "group", "group2"], value_vars=["col1", "col2"]),
    x="x-axis", y="value", style="variable", hue="group", col="group2", kind="line")

Output:

这篇关于如何在seaborn python中组合两个relplots?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆