Reputation: 336
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.
Upvotes: 2
Views: 2471
Reputation: 40747
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))
Upvotes: 4