最适合直方图 Iris

问题描述

我想为每个特征直方图绘制每个 Iris 类的最佳拟合线。 我已经尝试了以下示例中的解决方案:12,但没有得到我想要的结果。

这是直方图现在的样子,也是我希望它们的样子,但每个类都有一条最佳拟合线。

Imgae

这是我用来实现此目的的代码

df2 = df.T
df2.columns = df2.iloc[0]
df2 = df2.iloc[1:].reset_index(drop=True)
df2.head(2)

解决方法

使用 seaborn,您可以通过 sns.histplot(...,kde=True) 添加 kde curve。下面是一个例子:

import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm
import pandas as pd

sns.set()
iris = sns.load_dataset('iris')
# make the 'species' column categorical to fix the order
iris['species'] = pd.Categorical(iris['species'])

fig,axs = plt.subplots(2,2,figsize=(12,6))
for col,ax in zip(iris.columns[:4],axs.flat):
    sns.histplot(data=iris,x=col,kde=True,hue='species',common_norm=False,legend=ax==axs[0,0],ax=ax)
plt.tight_layout()
plt.show()

sns.histplot with kde

sns.histplot() 的一些参数:

  • common_norm=:当 True(默认)根据属于每个色调值的行数缩小每条曲线(或直方图)时
  • stat=:“计数”,“频率”,“密度”,“概率”`之一;确定 y 轴如何缩放
  • multiple=“layer”:默认,都在同一个位置;“dodge”:条形相邻; “stack”:条形和/或曲线堆叠; “fill”: for each x-value the bars (and/or curves) are stacked to sum to 1`。