【问题标题】:How to modify the kernel density estimate line in a sns.histplot如何修改 sns.histplot 中的核密度估计线
【发布时间】:2021-10-11 19:29:10
【问题描述】:

我正在创建一个直方图(频率与计数),我想添加不同颜色的核密度估计线。我怎样才能做到这一点?例如,我想更改颜色

sns.histplot(data=penguins, x="flipper_length_mm", kde=True)

示例取自https://seaborn.pydata.org/generated/seaborn.histplot.html

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

    histplotline_kws={...} 旨在更改 kde 行的外观。但是,当前的 seaborn 版本不允许以这种方式更改颜色,可能是因为颜色与 hue 参数一起使用(尽管在这种情况下未使用 hue)。

    import seaborn as sns
    
    penguins = sns.load_dataset('penguins')
    ax = sns.histplot(data=penguins, x="flipper_length_mm", kde=True,
                      line_kws={'color': 'crimson', 'lw': 5, 'ls': ':'})
    

    seaborn's github中,建议分别绘制histplotkdeplot。为了使两者在 y 方向上匹配,必须使用 histplotstat='density'kdeplot 没有使用 histplot 的默认值 stat='count' 的参数)。

    penguins = sns.load_dataset('penguins')
    ax = sns.histplot(data=penguins, x="flipper_length_mm", kde=False, stat='density')
    sns.kdeplot(data=penguins, x="flipper_length_mm", color='crimson', ax=ax)
    

    如果确实需要 count 统计信息,另一种方法是通过 matplotlib 更改线条颜色:

    penguins = sns.load_dataset('penguins')
    ax = sns.histplot(data=penguins, x="flipper_length_mm", kde=True)
    ax.lines[0].set_color('crimson')
    

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 2017-05-09
      • 1970-01-01
      • 2022-08-22
      • 2018-10-06
      • 2021-01-25
      • 2020-04-18
      • 2013-04-21
      • 2018-09-22
      相关资源
      最近更新 更多