繁体   English   中英

仅使用 seaborn pairplot 绘制一些列

[英]Plot only some columns with seaborn pairplot

我正在研究这个包含许多列的糖尿病数据集

通常,我可以使用此代码选择一些我需要的特定列:

import seaborn as sns
import matplotlib.pyplot as plt

plt.figure()
sns.pairplot(dataset_copy, vars=['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness'], hue = "Outcome", markers=["o", "s"])
plt.show()

如何使用幻灯片索引来选择列? 因为我想绘制所有列,但它会返回很多难以看到的图。

我只想绘制前 3 列,然后是剩余的。

# Plot the first 3 columns
plt.figure()
sns.pairplot(dataset_copy[:, 1:3], hue = "Outcome", markers=["o", "s"])
plt.show()

# Plot the remain columns
plt.figure()
sns.pairplot(dataset_copy[, 3:], hue = "Outcome", markers=["o", "s"])
plt.show()

使用此代码,我将收到此错误:

TypeError: '(slice(None, None, None), slice(1, 3, None))' is an invalid key

更新:使用iloc方法得到这个错误:

plt.figure()
sns.pairplot(dataset_copy.iloc[:, 1:3], hue = "Outcome", markers=["o", "s"])
plt.show()

在此处输入图像描述

编辑:在更彻底地检查数据之后,我明白这个问题有点微妙,尤其是在可视化方面:虽然你想对你选择的列进行子集化,因为你将传递到sns.pairplotdata参数中。 sns.pairplot ,这些列还必须包含“结果”,因此您可以根据此列改变 pairplot 的色调/颜色。 解决此问题的一种可能方法如下:


# Plot the first 3 columns
plt.figure()
cols_to_plot = dataset_copy.columns[1:3].tolist() + ['Outcome'] # explicitly add the column "Outcome" to your list of columns to plot
sns.pairplot(dataset_copy[cols_to_plot], hue ="Outcome", markers=["o", "s"])
plt.show()

# Plot the remain columns
plt.figure()
cols_to_plot = dataset_copy.columns[3:].tolist() # Take the remaining columns for the second plot; those already include "Outcome"
sns.pairplot(dataset_copy[cols_to_plot], hue = "Outcome", markers=["o", "s"])
plt.show()

这返回

first_3_cols

对于第一个图表。

如果您不喜欢单独创建cols_to_plot变量,还可以执行以下操作:

sns.pairplot(dataset_copy, vars = dataset_copy.columns[1:3], hue ="Outcome", markers=["o", "s"])

有效地将整个数据框传递到pairplot ,但只选择绘制特定的列子集,作为列表传递给vars参数。


原来的:

你上面的内容似乎是正确的。 代替

dataset_copy[:, 1:3]

利用

dataset_copy.iloc[:, 1:3]

发生错误是因为在使用方括号切片时,您可以要求获取行(例如df[0:5]获取某些特定列(例如df['Alpha'] )。 要同时按索引和列进行切片,您需要使用iloc (用于基于位置的索引)或loc (用于基于标签的索引)。 请参阅 Pandas 文档中的更详细说明

可以使用以下方式

import seaborn as sns import matplotlib.pyplot as plt plt.figure() sns.pairplot(dataset_copy[['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Outcome']], hue = "Outcome", markers=["o", "s"]) plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM