2

I am trying to use both style and hue in my points to visualise my data using seaborn. See the below example.

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('tips')
grid = sns.FacetGrid(data=df, row='smoker', col='day', hue='time', sharex=False, sharey=False)
grid.map_dataframe(sns.scatterplot, x='total_bill', y='tip', style='sex')
grid.add_legend()

The output is as below. I want to also be able to see the differentiation by sex in the legend. How can I achieve this? For example Blue x - male lunch, Blue * - Female lunch, Orange x - Male dinner, Orange * - Female dinner. If I can even do the same using sns.catplot or any other method that is also fine.

Output

Hawklaz
  • 306
  • 4
  • 20

1 Answers1

4

You have to move the hue= and style= to the call to scatterplot()

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('tips')
grid = sns.FacetGrid(data=df, row='smoker', col='day', sharex=False, sharey=False)
grid.map_dataframe(sns.scatterplot, x='total_bill', y='tip', hue='time', style='sex')
grid.add_legend()

However, you need to heed the warning in the FacetGrid documentation:

Warning

When using seaborn functions that infer semantic mappings from a dataset, care must be >taken to synchronize those mappings across facets (e.g., by defing the hue mapping with >a palette dict or setting the data type of the variables to category). In most cases, it >will be better to use a figure-level function (e.g. relplot() or catplot()) than to use >FacetGrid directly.

If the defaults are appropriate for you, you'd be better off using sns.relplot():

sns.relplot(data=df, row='smoker', col='day', x='total_bill', y='tip', hue='time', style='sex', facet_kws=dict(sharex=False, sharey=False))
Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
  • Quick additional question, how can I get the xlabel and ylabel to show using the given x and y? I am aware I can do [this](https://stackoverflow.com/a/55920946/11542679) but can't I just set it to add the given labels? I noticed the axes labels are omitted when I use the solution with `FacetGrid` along with `map_dataframe`. – Hawklaz Dec 05 '20 at 12:51