0

我看了很多视频,阅读了 Seaborn 文档,查看了很多网站,但我仍然没有找到问题的答案。

这来自 Seaborn 文档:

iris = sns.load_dataset("iris")
ax = sns.boxplot(data=iris, orient="h", palette="Set2")

此代码为单个图形中的每个数值变量创建箱线图。

鸢尾花数据集的箱线图

当我尝试添加 hue= "species" 时,ValueError: Cannot use huewithout xand y。有没有办法用 Seaborn 做到这一点?我想查看所有数值变量的箱线图并探索分类变量。因此,该图将显示每个物种的所有数值变量。由于有 3 个物种,箱线图的总数为 12(3 个物种乘以 4 个数值变量)。

我正在学习 EDA(探索性数据分析)。我认为上图将帮助我一次探索许多变量。

感谢您花时间阅读我的问题!

4

1 回答 1

3

要应用“色调”,seaborn 需要“长”形式的数据框。df.melt()是一个可以在这里提供帮助的 pandas 函数。它将数字列转换为 2 个新列:一个称为“变量”,具有列的旧名称,另一个称为“值”,具有值。生成的数据帧将是 4 倍长,因此“值”可以用于x=,“变量”可以用于y=

长格式如下所示:

物种 多变的 价值
0 濑户 萼片长度 5.1
1 濑户 萼片长度 4.9
2 濑户 萼片长度 4.7
3 濑户 萼片长度 4.6
4 濑户 萼片长度 5.0
... ... ...
import seaborn as sns
from matplotlib import pyplot as plt

iris = sns.load_dataset("iris")
iris_long = iris.melt(id_vars=['species'])
ax = sns.boxplot(data=iris_long, x="value", y="variable", orient="h", palette="Set2", hue="species")
plt.tight_layout()
plt.show()

带色调的箱线图

于 2021-03-27T21:19:31.320 回答