首页 > 解决方案 > 如何将标签添加到pairplot?

问题描述

我有一个具有以下形式的数据框:

          0         1         2         3  ...         9        10       11     output
0  2.451775  1.9565675  0.843128 -0.007820  ...  0.74554812  0.090777 -1.90625       a
1 -0.855458 -0.8444604 -0.619685  0.2273399  ... 1.3771857   4.089319 -0.16289       a
2  1.554580  1.9164567  0.643128 -0.0077550  ... 0.7771542   5.090777 -1.90625       b

这是标准化 numpy 数组并添加最后一列名为 output 的结果。我添加了最后一列,以便能够在带有 hue=output 的 sns.pairplot 中使用它。

我遇到的问题是我的配对图显示有这样的数字: 在此处输入图像描述

所以我想要的是显示而不是数字 0,1,2,.., 一组标签,因此我有一个标签列表,例如:

labels=["label 1","label 2",...,"label n" ]

我想添加到我的pairplot中以使用标签名称而不是索引号0、1、...n-1。我做了以下事情:

sns.pairplot(df,vars=labels,hue="output")

但我收到以下错误:

KeyError: 'label 1'

我尝试了`reset_index(drop = True)的选项,但根本没有结果。我怎样才能解决这个问题?

谢谢

标签: pythonpandasseaborn

解决方案


我认为您可以通过从“matplotlib”轴获取信息并设置它来做到这一点。

labels=["label 1","label 2",...,"label n" ]
g = sns.pairplot(df,vars=labels,hue="output")

for ax, lbl in zip(g.axes.flatten(), labels):
    # print(ax, lbl)
    ax.set_ylabel(f'{lbl}')

推荐阅读