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)

enter image description here

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.

Upvotes: 0

Views: 415

Answers (2)

JohanC
JohanC

Reputation: 80319

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

sns.FacetPlot with two line plots

Upvotes: 0

mwaskom
mwaskom

Reputation: 49002

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,
)

enter image description here

Upvotes: 1

Related Questions