Have gradient colours in sns.pairplot for one column of dataframe so that I can see which datapoints are connected to each other

Viewed 341

I am quite easily able to produce a seaborn pairplot with:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

f, axes = plt.subplots(1, 1)

np.random.seed(1)
a = np.arange(0, 10, 0.1)

np.random.rand()

def myFunc(x):
    myReturn = x + 1*np.random.random(x.shape[0])
    return myReturn

b = myFunc(a)
c = a * np.sin(a)

df = pd.DataFrame({'a': a, 'b': b, 'c': c})

sns.pairplot(df, corner=True)
plt.show()

I would like to see the interdependence of my data more easily.

For that I want to have a gradual color gradient for one column of my DataFrame (so that low numerical values of that column are e.g. yellow and high values are blue).

These colors should be shown for all non diagonal subplots of my plot, based on the data points of a, see sketch below.

The benefit for this is limited for the [a, b] and [a, c] plots, but for the [b, c] plot I would expect more insights, if the data gets more complicated.

How would the syntax for this would like?

enter image description here

2 Answers

You could loop through the off-diagonal axes. And then change the colormap and color values for the scatterplots:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import seaborn as sns
import pandas as pd
import numpy as np

def myFunc(x):
    myReturn = x + 1 * np.random.random(x.shape[0])
    return myReturn

np.random.seed(1)
a = np.arange(0, 10, 0.1)
np.random.rand()

b = myFunc(a)
c = a * np.sin(a)
df = pd.DataFrame({'a': a, 'b': b, 'c': c})

cmap = LinearSegmentedColormap.from_list('blue-yellow', ['gold', 'lightblue', 'darkblue'])  # plt.get_cmap('viridis_r')
g = sns.pairplot(df, corner=True)
for ax in g.axes.flat:
    if ax is not None and not ax in g.diag_axes:
        for collection in ax.collections:
            collection.set_cmap(cmap)
            collection.set_array(df['a'])
plt.show()

changing the scatterplots of a sns.pairplot

I think the much easier thing to do here is to pass the dataframe index as a hue variable. Since you don't want to (naively) apply to the histogram, pass it directly to the off-diagonal plots:

sns.pairplot(
    df,
    corner=True,
    diag_kws=dict(color=".6"),
    plot_kws=dict(
        hue=df.index,
        palette="blend:gold,dodgerblue",
    ),
)

enter image description here

Related