简体   繁体   中英

Seaborn legend not showing style, only showing hue

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.

输出

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM