Seaborn Pairplot 有和没有色调在彼此之上

Seaborn Pairplot with and without hue on top of each other

我正在将数据框绘制为配对图,并在 seaborn 中使用 regplot 拟合低线。我使用了 hue = "variable",但也希望在同一 pairplot 中看到适合整个数据(非色调)的最低线。对于这个问题的任何帮助或提示,我将不胜感激。

pg = sns.pairplot(df, hue="variable", plot_kws={'alpha':0.015})

a = pg.map(sns.regplot, lowess=True, scatter_kws={'alpha':0.03})

让我们用自定义函数替换 sns.regplot,例如plot_extra.

pg.map 将为每个子图的每个色调值调用一次 plot_extra。它将传递以下参数:

  • label:本次调用的色调值名称
  • xy:此子图的列,仅限于当前色调值
  • 调用 pg.map
  • 时给出的额外参数

要为完整的数据框绘制regplot,可以将数据框作为额外参数给出。为了防止对每个色调值一次又一次地执行相同的功能,该功能可以在标签上进行测试,并且只对一个特定的标签进行进一步测试。 xy.name 可用于指示绘制哪些列。 .map() 将调用每个子图,而 .map_offdiag() 将被限制为不在对角线上的子图。

可以更新图例:从现有 pairplot 图例中提取信息并添加对 regplot 线的引用。

这是一个使用标准鸢尾花数据集的示例。

import matplotlib.pyplot as plt
import seaborn as sns

def plot_extra(x, y, **kwargs):
     if kwargs['label'] == first_label:
          sns.regplot(data=kwargs['data'], x=x.name, y=y.name, lowess=True, scatter=False, color=kwargs['color'])

df = sns.load_dataset('iris')

first_label = df['species'][0]
pg = sns.pairplot(df, hue='species', plot_kws={'alpha': 0.5}, palette='turbo')

pg.map_offdiag(plot_extra, color='crimson', data=df)

legend_dict = {h.get_label(): h for h in pg.legend.legendHandles}  # the existing legend items
legend_dict['lowess regression'] = pg.axes[0, 1].lines[
     0]  # add the first line object of a non-diagonal ax to the legend

pg.legend.remove()  # remove existing legend
pg.add_legend(legend_dict, label_order=legend_dict.keys(), title='')  # create the new legend
plt.show()