Plot lower triangle in a seaborn Pairgrid

2020-05-27 10:56发布

I'm a bit struggling with seaborn Pairgrid.

Let's say I have a Pairgrid like this:

enter image description here

As you can see, the upper triangle plots mirror the lower triangle ones. I'd like to be able to plot only the lower triangle plots, but I found no easy way so far to do it. Can you help me?

2条回答
Lonely孤独者°
2楼-- · 2020-05-27 11:24

Probably should be an easier way, but this works

import numpy as np
import seaborn as sns
iris = sns.load_dataset("iris")
g = sns.pairplot(iris)
for i, j in zip(*np.triu_indices_from(g.axes, 1)):
    g.axes[i, j].set_visible(False)

enter image description here

查看更多
ら.Afraid
3楼-- · 2020-05-27 11:37

this is basically the same as the accepted answer, but uses the official methods from seaborn.PairGrid:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
iris = sns.load_dataset("iris")

def hide_current_axis(*args, **kwds):
    plt.gca().set_visible(False)

g = sns.pairplot(iris)
g.map_upper(hide_current_axis)

hiding the lower half is also easy:

g.map_lower(hide_current_axis)

or hiding the diagonal:

g.map_diag(hide_current_axis)

alternatively, just use the PairGrid directly for more control:

from itertools import groupby

def stackedhist(data, stackby, **kwds):
    groups = groupby(zip(stackby, data), lambda x: x[0])
    grouped_data = [[v for _, v in items] for key, items in groups]
    plt.hist(grouped_data, stacked=True, edgecolor='none')

g = sns.PairGrid(iris, diag_sharey=False)
g.map_lower(sns.scatterplot, data=iris, hue='species', alpha=0.3, edgecolor='none')
g.map_diag(stackedhist, stackby=iris['species'])
g.map_upper(hide_current_axis)

which gives:

money shot

查看更多
登录 后发表回答