【问题标题】:Emulating deprecated seaborn distplots模拟已弃用的 seaborn 分布图
【发布时间】:2021-08-10 18:46:57
【问题描述】:

Seaborn distplot 现已弃用,将在未来版本中删除。建议使用histplot(或displot作为图形级图)作为替代方案。但是distplothistplot 之间的预设不同:

from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns

x_list = [1, 2, 3, 4, 6, 7, 9, 9, 9, 10]
df = pd.DataFrame({"X": x_list, "Y": range(len(x_list))})

f, (ax_dist, ax_hist) = plt.subplots(2, sharex=True)

sns.distplot(df["X"], ax=ax_dist)
ax_dist.set_title("old distplot")
sns.histplot(data=df, x="X", ax=ax_hist)
ax_hist.set_title("new histplot")

plt.show()

那么,我们如何配置histplot 以复制已弃用的distplot 的输出?

【问题讨论】:

    标签: python matplotlib seaborn histogram kernel-density


    【解决方案1】:

    由于我花了一些时间在这方面,我想我分享一下,以便其他人可以轻松地适应这种方法:

    from matplotlib import pyplot as plt
    import pandas as pd
    import seaborn as sns
    import numpy as np
    
    x_list = [1, 2, 3, 4, 6, 7, 9, 9, 9, 10]
    df = pd.DataFrame({"X": x_list, "Y": range(len(x_list))})
    
    f, (ax_dist, ax_hist) = plt.subplots(2, sharex=True)
    
    sns.distplot(df["X"], ax=ax_dist)
    ax_dist.set_title("old distplot")
    _, FD_bins = np.histogram(x_list, bins="fd")
    bin_nr = min(len(FD_bins)-1, 50)
    sns.histplot(data=df, x="X", ax=ax_hist, bins=bin_nr, stat="density", alpha=0.4, kde=True, kde_kws={"cut": 3})
    ax_hist.set_title("new histplot")
    
    plt.show()
    

    样本输出:

    主要变化是

    • bins=bin_nr - 使用Freedman Diaconis Estimator 确定直方图箱并将上限限制为 50
    • stat="density" - 在直方图中显示密度而不是计数
    • alpha=0.4 - 相同的透明度
    • kde=True - 添加核密度图
    • kde_kws={"cut": 3} - 将核密度图扩展到直方图限制之外

    关于bins="fd" 的bin 估计,我不确定这是否确实是distplot 使用的方法。非常欢迎评论和更正。

    我删除了**{"linewidth": 0},因为正如@mwaskom 在评论中指出的那样,distplot 在直方图条周围有一条edgecolor 线,可以由matplotlib 设置为默认的facecolor。因此,您必须根据自己的风格偏好对其进行分类。

    【讨论】:

    • 您也可以将alpha=0.4 添加到histplot
    • 很好看。我的印象是颜色略有偏差,但没有遵循这个想法。
    • "关于 bins="fd" 的 bin 估计,我不确定这是否确实是 distplot 使用的方法。欢迎评论和更正。这基本上是正确的; histplot 使用 numpy 的 "auto" 模式,它采用 FD 和 Sturges 估计器的最大值。唯一难以完全复制的是distplot 默认使用min(FD_bins, 50)。因此,如果您真的想要完全相同的行为,则需要在外部进行。
    • 哦,linewidth=0 也错了; distplot 条形有可见边缘,但在 matplotlib 的默认设置中,条形边缘颜色设置为 "face"。如果您激活其中一个 seaborn 主题,您会看到不同之处。
    • @Mr.T distplot 使用an“优化”方法(相对于固定数量的 bin),但有许多不同的参考规则可以更好地工作或对于不同类型的数据更糟...... numpy 的"auto" 试图平衡两个最常见的数据。实际上在编写distplot 时,numpy 并没有实现任何引用规则,所以distplot 在内部实现了FD 规则。一旦 numpy 添加了 bins="auto" 并连接到 numpy 进行计算,就可以通过 bins="auto",但默认仍然使用内部 FD 计算,有上限。
    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 2016-08-30
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2019-03-11
    • 2018-05-30
    相关资源
    最近更新 更多