3

Using seaborn's FacetGrid, I'd like to update the 'hue' grouping parameter between multiple mapping calls. Specifically, I initially have a custom plotting function that takes a 'hue' grouping, on top of which I want to show the average across groups (so ignoring hue, and summarizing all the data).

e.g.

g = sns.FacetGrid(tips, col="time",  hue="smoker")
g = (g.map(plt.scatter, "total_bill", "tip", edgecolor="w").add_legend())
g = (g.map(sns.regplot, "total_bill", "tip").add_legend())

Will create one colored regression line for each group. How can I update FacetGrid to ignore the hue grouping on the second call to map? In this example, I want to have two colored scatter plots with a single (black) regression line overlaid.

anne
  • 31
  • 2
  • You can find elements of answer here : https://stackoverflow.com/questions/64432872/how-to-overlay-two-sns-catplots/64597529#64597529 – Maxime Beau Oct 30 '20 at 09:31

1 Answers1

1

The hue is used by FacetGrid to group the input data. It cannot group it only partially.

A matplotlib solution would probably look like

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips", cache=True)

n = len(tips["time"].unique())
usmoker = tips["smoker"].unique()

fig, axes = plt.subplots(ncols=n, sharex=True, sharey=True)

for ax, (time, grp1) in zip(axes.flat, tips.groupby("time")):
    ax.set_title(time)
    ax.set_prop_cycle(plt.rcParams["axes.prop_cycle"])

    for smoker in usmoker:
        grp2 = grp1[grp1["smoker"] == smoker]
        sns.regplot("total_bill", "tip", data=grp2, label=str(smoker), 
                    fit_reg=False, ax=ax)
    ax.legend(title="Smoker")  

for ax, (time, grp1) in zip(axes.flat, tips.groupby("time")):
    sns.regplot("total_bill", "tip", data=grp1, ax=ax, scatter=False, 
                color="k", label="regression line")


plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712