问题
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.
回答1:
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:
来源:https://stackoverflow.com/questions/58034473/how-to-combine-two-relplots-in-seaborn-python