模拟已弃用的seaborn distplots

问题描述 投票:0回答:2

Seaborn

distplot
现已弃用,并将在未来版本中删除。建议使用
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()

那么,我们如何配置

histplot
来复制已弃用的
distplot
的输出?

python matplotlib seaborn histogram kernel-density
2个回答
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()

输出示例:

主要变化是

  • 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
。所以,你必须根据你的风格偏好来解决这个问题。


0
投票

#使用 histplot() #histplot 用于单变量

将seaborn导入为sns 将 matplotlib.pyplot 导入为 plt

fig = sns.FacetGrid(data = data, col = '变量名称',hue = '变量名称',heigth = 9,palette = 'Set1')

fig = Fig.map(sns.histplot, 变量名, kde = True).add_legend()

© www.soinside.com 2019 - 2024. All rights reserved.