I want to plot two lines on the same set of axes. It seems sns.relplot
is creating a facetted figure, and I don’t know how to specify that I want the second line on the same facet as the first.
Here’s a MWE
JavaScript
x
12
12
1
import numpy as np
2
import pandas as pd
3
import seaborn as sns
4
5
x = np.random.uniform(low = 1, high = 10, size = 20)
6
7
df1 = pd.DataFrame({'x': x, 'y1': 2 * x, 'type': 'a'})
8
df2 = pd.DataFrame({'x': x, 'y2': 3 * x, 'type': 'b'})
9
10
sns.relplot(data = df1, x = 'x', y = 'y1', kind = 'line', hue = 'type', palette = ['red'])
11
sns.relplot(data = df2, x = 'x', y = 'y2', kind = 'line', hue = 'type', palette = ['blue'])
12
How do I get the red and blue lines on the same plot? I’ve not had luck with different permutations of map.
Advertisement
Answer
seaborn.relplot
is aFacetGrid
, the dataframes should be combined to plot them together- Figure-level interface for drawing relational plots onto a
FacetGrid
.- This function provides access to several different axes-level functions that show the relationship between two variables with semantic mappings of subsets. The
kind
parameter selects the underlying axes-level function to use:scatterplot()
(with kind=”scatter”; the default)lineplot()
(with kind=”line”)
- This function provides access to several different axes-level functions that show the relationship between two variables with semantic mappings of subsets. The
- Figure-level interface for drawing relational plots onto a
- Tested in
python 3.8.12
,pandas 1.3.4
,matplotlib 3.4.3
,seaborn 0.11.2
JavaScript
1
16
16
1
import pandas as pd
2
import numpy as np
3
import seaborn as sns
4
import matplotlib.pyplot as plt
5
6
np.random.seed(2022) # to create the same sample data
7
x = np.random.uniform(low=1, high=10, size=20)
8
9
df1 = pd.DataFrame({'x': x, 'y1': 2 * x, 'type': 'a'})
10
df2 = pd.DataFrame({'x': x, 'y2': 3 * x, 'type': 'b'}).rename(columns={'y2': 'y1'})
11
12
df = pd.concat([df1, df2], ignore_index=True)
13
14
# plot df
15
g = sns.relplot(data=df, x='x', y='y1', kind='line', hue='type', palette=['red', 'blue'])
16
Alternatives
- Create a separate
seaborn.lineplot
for each dataframe.
JavaScript
1
11
11
1
np.random.seed(2022)
2
x = np.random.uniform(low = 1, high = 10, size = 20)
3
4
df1 = pd.DataFrame({'x': x, 'y1': 2 * x, 'type': 'a'})
5
df2 = pd.DataFrame({'x': x, 'y2': 3 * x, 'type': 'b'})
6
7
fig, ax = plt.subplots(figsize=(5, 5))
8
9
sns.lineplot(data=df1, x='x', y='y1', label='a', ax=ax)
10
sns.lineplot(data=df2, x='x', y='y2', label='b', ax=ax)
11
- Plot the dataframes directly, without seaborn
JavaScript
1
3
1
ax = df1.plot(x='x', figsize=(5, 5))
2
df2.plot(x='x', ax=ax)
3