模拟已弃用的seaborn distplots

Mr.*_*. T 4 python matplotlib histogram kernel-density seaborn

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

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

Mr.*_*. T 6

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

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()
Run Code Online (Sandbox Code Playgroud)

示例输出:
在此输入图像描述

主要变化是

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

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

我删除了,**{"linewidth": 0}因为distplot正如 @mwaskom 在评论中指出的那样,edgecolor直方图条周围有一条线,可以由 matplotlib 设置为默认值facecolor。所以,你必须根据你的风格偏好来解决这个问题。

  • “关于 bins="fd" 的 bin 估计,我不确定这确实是 distplot 使用的方法。非常欢迎评论和更正。” 这基本上是正确的;`histplot` 使用 numpy 的 `"auto"` 模式,该模式采用 FD 和 Sturges 估计器的最大值。唯一难以完全复制的是“distplot”默认使用“min(FD_bins, 50)”。因此,如果您确实想要“完全相同”的行为,则需要在外部执行此操作。 (2认同)
  • 哦,`linewidth=0` 也是错误的;`distplot` 条形图具有可见的边缘,但使用 matplotlib 默认情况下,条形图边缘颜色设置为 `"face"`。如果您激活seaborn 主题之一,您就会看到差异。 (2认同)