Tricks
Tricks

Reputation: 3

Customize Seaborn Pair Grid

I'm trying to use Seaborn Pair Grid to make a correlogram with scatterplots in one half, histograms on the diagonal and the pearson coefficient on the other half. I've managed to put together the following code which does what I need, but I'm really struggling with further customization

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import pearsonr

df = sns.load_dataset('iris')

def reg_coef(x,y,label=None,color=None,**kwargs):
    ax = plt.gca()
    r,p = pearsonr(x,y)
    ax.annotate('{:.2f}'.format(r), xy=(0.5,0.5), xycoords='axes fraction', ha='center',fontsize=30,
               bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 20})
    ax.set_axis_off()

 
    
sns.set(font_scale=1.5)
sns.set_style("white")


g = sns.PairGrid(df)
g.map_diag(plt.hist)
g.map_lower(plt.scatter)
g.map_upper(reg_coef)

g.fig.subplots_adjust(top=0.9)
g.fig.suptitle('Iris Correlogram', fontsize=30)
    
plt.show()

This is the result

What I'd like to do:

  1. Change the font used for the whole plot and assign my own defined rgb colour to the font and axes (same one)
  2. Remove the X & Y tick labels
  3. Change the colour of the scatter dots and histogram bars to my own defined rgb colour (same one)
  4. Set a diverging colour map for the background of the pearson number to highlight the degree and type of correlation, again using my own defined rgb colours.

I know Im asking a lot but Ive spent hours going round in circles trying to figure this out!!

Upvotes: 0

Views: 1345

Answers (1)

JohanC
JohanC

Reputation: 80449

The color can be set as extra parameter in g.map_diag(plt.hist, color=...) and g.map_lower(plt.scatter, color=...). The function reg_coef can be modified to take a colormap into account.

The font color and family can be set via the rcParams. The ticks can be removed via plt.setp(g.axes, xticks=[], yticks=[]). Instead of subplot_adjust, g.fig.tight_layout() usually fits all elements nicely into the plot. Here is an example:

import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import pearsonr

def reg_coef(x, y, label=None, color=None, cmap=None, **kwargs):
    ax = plt.gca()
    r, p = pearsonr(x, y)
    norm = plt.Normalize(-1, 1)
    cmap = cmap if not cmap is None else plt.cm.coolwarm
    ax.annotate(f'{r:.2f}', xy=(0.5, 0.5), xycoords='axes fraction', ha='center', fontsize=30,
                bbox={'facecolor': cmap(norm(r)), 'alpha': 0.5, 'pad': 20})
    ax.set_axis_off()

df = sns.load_dataset('iris')

sns.set(font_scale=1.5)
sns.set_style("white")
for param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']:
    plt.rcParams[param] = 'cornflowerblue'
plt.rcParams['font.family'] = 'cursive'

g = sns.PairGrid(df, height=2)
g.map_diag(plt.hist, color='turquoise')
g.map_lower(plt.scatter, color='fuchsia')
g.map_upper(reg_coef, cmap=plt.get_cmap('PiYG'))
plt.setp(g.axes, xticks=[], yticks=[])

g.fig.suptitle('Iris Correlogram', fontsize=30)
g.fig.tight_layout()
plt.show()

seaborn pairplot with custom colors and fonts

Upvotes: 1

Related Questions