python - 模拟已弃用的 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
?
解决方案
由于我花了一些时间在这方面,我想我分享一下,以便其他人可以轻松地适应这种方法:
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,并将上限限制为 50stat="density"
- 在直方图中显示密度而不是计数alpha=0.4
- 对于相同的透明度kde=True
- 添加核密度图kde_kws={"cut": 3}
- 将核密度图扩展到直方图限制之外
关于 bin 估计bins="fd"
,我不确定这确实是distplot
. 非常欢迎评论和更正。
我删除了,**{"linewidth": 0}
因为distplot
正如@mwaskom 在评论中指出的那样,edgecolor
直方图条周围有一条线,可以由 matplotlib 设置为 default facecolor
。因此,您必须根据自己的风格偏好对其进行分类。
推荐阅读
- amazon-web-services - S3ToRedshiftTransfert 在创建的表中返回 0 元素
- azure - WebSocket 握手期间出错:意外的响应代码:在 azure 上与 ocelot 网关连接时出现 502
- reactjs - 为什么要在 url %E2%80%8B 中获取 api 添加转义字符
- sql - 如何从 SQL Server 表中提取第二高的产品使用率?
- r - 数据序列 - 如何提取与时间序列中的时间相关的特定数据
- java - Java 使用 Stream 按值对映射进行排序
- swift - 我可以在 ARView 中使用缩放功能吗?
- gdb - CLion如何在exec'd进程中设置断点
- excel - 通过选择特定行,使用 VBA 将 Excel 链接到 Word 文档
- python - 没有正确插入简单的 Varchar?生成字符串