【问题标题】:Seaborn legend not showing style, only showing hueSeaborn 传奇不显风采,只显色相
【发布时间】:2021-03-16 13:40:57
【问题描述】:

我试图在我的观点中同时使用stylehue 来使用seaborn 可视化我的数据。请参见下面的示例。

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

输出如下。我也希望能够看到传说中的性别差异。我怎样才能做到这一点?例如,蓝色 x - 男性午餐,蓝色 * - 女性午餐,橙色 x - 男性晚餐,橙色 * - 女性晚餐。如果我什至可以使用sns.catplot 或任何其他方法也可以做到这一点。

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    您必须将hue=style= 移动到对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()
    

    但是,您需要注意 FacetGrid 文档中的警告:

    警告

    当使用从数据集推断语义映射的 seaborn 函数时,必须注意>跨方面同步这些映射(例如,通过使用调色板字典定义色调映射或将变量的数据类型设置为类别) .在大多数情况下,> 使用图形级函数(例如 relplot() 或 catplot())比直接使用 >FacetGrid 更好。

    如果默认值适合您,您最好使用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))
    

    【讨论】:

    • 快速附加问题,如何使用给定的 x 和 y 显示 xlabel 和 ylabel?我知道我可以做this 但我不能设置它来添加给定的标签吗?我注意到当我将解决方案与FacetGridmap_dataframe 一起使用时,轴标签被省略了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    相关资源
    最近更新 更多