首页 > 解决方案 > 模拟已弃用的 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()

在此处输入图像描述

那么,我们如何配置histplot以复制 deprecated 的输出distplot

标签: pythonmatplotlibseabornhistogramkernel-density

解决方案


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

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确定直方图 bin,并将上限限制为 50
  • stat="density"- 在直方图中显示密度而不是计数
  • alpha=0.4- 对于相同的透明度
  • kde=True- 添加核密度图
  • kde_kws={"cut": 3}- 将核密度图扩展到直方图限制之外

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

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


推荐阅读