首页 > 解决方案 > 仅使用 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()

在此处输入图像描述

标签: pythonseaborn

解决方案


编辑:在更彻底地检查数据之后,我明白这个问题有点微妙,尤其是在可视化方面:虽然您想对您选择的列进行子集化,但由于您将这些列传递到data参数中还必须包括“结果”,因此您可以根据此列改变配对图的色调/颜色。解决此问题的一种可能方法如下:sns.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文档中的更详细说明


推荐阅读