使用 Seaborn 一次绘制数据集中所有变量的箱线图
Boxplots with Seaborn for all variables in a dataset at once
看了很多视频,看了Seaborn文档,查了很多网站,还是没找到问题的答案。
这来自 Seaborn 文档:
iris = sns.load_dataset("iris")
ax = sns.boxplot(data=iris, orient="h", palette="Set2")
此代码为单个图中的每个数值变量创建箱线图。
当我尝试添加 hue=“species”时,ValueError:无法在没有 x
和 y
的情况下使用 hue
。有没有办法用 Seaborn 做到这一点?我想查看所有数值变量的箱线图并探索分类变量。因此该图将显示每个物种的所有数值变量。由于有 3 个物种,箱线图的总数为 12(3 个物种乘以 4 个数值变量)。
我正在学习 EDA(探索性数据分析)。我认为上图将帮助我一次探索许多变量。
感谢您花时间阅读我的问题!
要应用“色调”,seaborn 需要 "long" form. df.melt()
中的数据框是一个 pandas 函数,可以在此处提供帮助。它将数字列转换为 2 个新列:一个称为“变量”的列的旧名称,另一个称为“值”的值。生成的数据帧将是 4 倍长,因此“值”可用于 x=
,“变量”可用于 y=
。
长格式如下:
species
variable
value
0
setosa
sepal_length
5.1
1
setosa
sepal_length
4.9
2
setosa
sepal_length
4.7
3
setosa
sepal_length
4.6
4
setosa
sepal_length
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()
看了很多视频,看了Seaborn文档,查了很多网站,还是没找到问题的答案。
这来自 Seaborn 文档:
iris = sns.load_dataset("iris")
ax = sns.boxplot(data=iris, orient="h", palette="Set2")
此代码为单个图中的每个数值变量创建箱线图。
当我尝试添加 hue=“species”时,ValueError:无法在没有 x
和 y
的情况下使用 hue
。有没有办法用 Seaborn 做到这一点?我想查看所有数值变量的箱线图并探索分类变量。因此该图将显示每个物种的所有数值变量。由于有 3 个物种,箱线图的总数为 12(3 个物种乘以 4 个数值变量)。
我正在学习 EDA(探索性数据分析)。我认为上图将帮助我一次探索许多变量。
感谢您花时间阅读我的问题!
要应用“色调”,seaborn 需要 "long" form. df.melt()
中的数据框是一个 pandas 函数,可以在此处提供帮助。它将数字列转换为 2 个新列:一个称为“变量”的列的旧名称,另一个称为“值”的值。生成的数据帧将是 4 倍长,因此“值”可用于 x=
,“变量”可用于 y=
。
长格式如下:
species | variable | value | |
---|---|---|---|
0 | setosa | sepal_length | 5.1 |
1 | setosa | sepal_length | 4.9 |
2 | setosa | sepal_length | 4.7 |
3 | setosa | sepal_length | 4.6 |
4 | setosa | sepal_length | 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()