如何将 pandas 数据框的变量名放在 Seaborn PairGrid 的对角线上?

数据挖掘 Python 熊猫 matplotlib 海运
2022-01-25 20:45:07

下面给出的代码现在不起作用(之前它起作用)将列名放在 Seaborn PairGrid 的对角线上。

import matplotlib.pyplot as plt
import seaborn as sns
iris = sns.load_dataset('iris')

def diagfunc(x, **kws):
  ax = plt.gca()
  ax.annotate(x.name, xy=(0.05, 0.9), xycoords=ax.transAxes)

sns.PairGrid(iris).map_diag(diagfunc)

在此处输入图像描述

目前它显示此错误!

<ipython-input-137-f4d9b71087cb> in diagfunc(x, **kws)
      5 def diagfunc(x, **kws):
      6     ax = plt.gca()
----> 7     ax.annotate(x.name, xy=(0.05, 0.9), xycoords=ax.transAxes)
      8 
      9 sns.PairGrid(iris).map_diag(diagfunc)

AttributeError: 'numpy.ndarray' object has no attribute 'name'

谁能帮我如何将列名放在对角线上?

1个回答

通过最小的更改,我得到了这个工作(python3.7.3,SeaBorn 0.9.0):

import matplotlib.pyplot as plt
import seaborn as sns
iris = sns.load_dataset('iris')

# Add this before your call to map_diag
next_iris_label = iter(iris).__next__

def diagfunc(x, **kws):
  ax = plt.gca()
  #  replace x.name with `next_iris_label` call
  ax.annotate(next_iris_label(), xy=(0.05, 0.9), xycoords=ax.transAxes)

sns.PairGrid(iris).map_diag(diagfunc)

输出: 在 JupyterLab 中运行时的上述 python 代码的输出

我深入研究并了解失败的原因是因为一旦将 IRIS 数据集传递给SeaBorn.PairGrid,就不会保留观察列的原始名称。map_diag最终调用diagfunc的对角线组件PairGrid,它们没有 name 属性,更不用说在传递的参数中的其他任何地方命名。这是传递给第一次diagfunc调用的内容:

{
    #  this is what you passed as positional parameter
    #  As you'll notice `x` is just an array, and 
    #   does not have any additional properties like a label
    'x': array([5.1, 4.9, , ... 5.9]), 
    #  these get passed in as **kws
    'label': '_nolegend_', 
    'color': (0.12156862745098039, 0.4666666666666667, 0.7058823529411765)
}

现在,如果我们能够以某种方式遍历 IRIS 数据集中的所有标签,我们就可以将每个标签与PairGrid. 由于diagfunc每次都被调用并且有一个新的范围,我发现有一个迭代器在每次被调用时都返回一个新的标签可以解决这个问题。

next_iris_label定义为

next_iris_label = iter(iris).__next__

解决了这个问题。这只有一个我不喜欢的约束,next_iris_label = iter(iris).__next__当您想再次进行此类标记时,您需要通过绑定语句创建迭代器的新实例来重置它(否则会引发 StopIteration 错误。)