'python seaborn: how to automatically give a different color to the lines in FacetGrid.map?
Suppose we want to use FacetGrid.map(sns.lineplot) twice on the same FacetGrid. May I ask how can we automatically get a different color in the second FacetGrid.map(sns.lineplot)?
Below is a minimal example to demonstrate the situation:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.FacetGrid(data=tips, height=6)
g.map(sns.lineplot, 'size', 'tip', ci=None)
g.map(sns.lineplot, 'size', 'total_bill', ci=None)
What I want is that the two lines are of different colors automatically. Thank you so much in advance!
PS: I know that I can alternatively use sns.lineplot twice instead of using g.map, but sns.lineplot doesn't allow me the flexibility to specify col and row parameters, and so I want to use g.map instead.
Solution 1:[1]
You would want to melt the dataframe so total_bill/tip are observations of the same variable:
sns.relplot(
data=tips.melt("size", ["total_bill", "tip"]),
x="size", y="value", hue="variable",
kind="line", ci=None,
)
Solution 2:[2]
You could convert the dataframe to "long form", and then use hue:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.FacetGrid(data=tips.melt(id_vars='size', value_vars=['tip', 'total_bill']), hue='variable', height=6)
g.map(sns.lineplot, 'size', 'value', ci=None)
# g.add_legend() # to add a figure-level legend
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mwaskom |
| Solution 2 | JohanC |



