Home > Back-end >  python seaborn: how to automatically give a different color to the lines in FacetGrid.map?
python seaborn: how to automatically give a different color to the lines in FacetGrid.map?

Time:04-18

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.

CodePudding user response:

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

CodePudding user response:

You could convert the dataframe to sns.FacetPlot with two line plots

  • Related