python - 仅使用 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()
解决方案
编辑:在更彻底地检查数据之后,我明白这个问题有点微妙,尤其是在可视化方面:虽然您想对您选择的列进行子集化,但由于您将这些列传递到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()
这返回
对于第一个图表。
如果您不喜欢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文档中的更详细说明
推荐阅读
- php - AWS 弹性 beantalk 上安装了哪些默认 php 扩展?
- javascript - 如何解决 ajax django 中的 JSONdecode 错误?
- c# - Unity - 使用按钮的 onClick 功能切换场景
- python - 有没有办法让 Eclipse(使用 pydev)在每个类或 def 语句的开头插入一个空的文档字符串?
- r - R中的Write.table循环
- ibm-watson - IBM Watson Visual Recognition:在端点 (...) 的 guid (...) 的 getAllCollections 响应中收到 403 中的无效状态
- maven - 在哪里可以找到 GCP 云构建者的列表?
- excel - (excel VBA):将记录集的剩余行复制到第二张表
- python - 为什么所有标签_都是-1?由 DBSCAN 在 Python 中生成
- c# - 有没有办法在泛型方法中提供任意数量的类型?