SerKo
SerKo

Reputation: 95

Proper diagonal Y axes for seaborn PairPlot

I'm trying to use seaborn pairplot for some visualizations and I need to have proper diagonal Y axes (visible!) with no normalization at all (just counts) or the density normalization (sum of bin values = 1). What is the better way to do it?

It is how I am trying to do it:

import numpy as np
import seaborn as sns
import pandas as pd

data = np.random.normal(0,2,[1000,3])

sss = sns.pairplot(pd.DataFrame(data),corner=True)
sss.axes[0][0].yaxis.tick_right()
sss.axes[0][0].get_yaxis().set_visible(True)
sss.axes[0][0].axis('on')
sss.axes[0][0].yaxis.set_label_position("right")
sss.axes[0][0].set_ylabel('Counts')

It gives me the following figure:

enter image description here

Evidently, I have the wrong normalization here (it is normalized on the maximum value, probably) and the y axis line itself is missing.

Upvotes: 3

Views: 2018

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40737

By default, the y-axes on each row are shared, and the y-axis of the diagonal plot is essentially meaningless.

If you want to plot something there and preserve the scale of the data you are trying to plot, then you should "break" the shared axes somehow. The easiest way I can think of is to create a new axes at the same position using twinx().

Of course, for this you need to be using PairGrid() instead of pairplot():

import numpy as np
import seaborn as sns
import pandas as pd

def my_hist(x, label, color):
    ax0 = plt.gca()
    ax = ax0.twinx()
    
    sns.despine(ax=ax, left=True, top=True, right=False)
    ax.yaxis.tick_right()
    ax.set_ylabel('Counts')
    
    ax.hist(x, label=label, color=color)

data = np.random.normal(0,2,[1000,3])
df = pd.DataFrame(data)

g = sns.PairGrid(df,corner=True)
g.map_diag(my_hist)
g.map_lower(sns.scatterplot)

enter image description here

Upvotes: 6

Related Questions