How to change the "shape" of pairplot in Seaborn?

359 Views Asked by At

I plotted this pairplot correlating only one features with all the others, how can i visualize it in a better way? I need to visualize 4 columns. In the official documentation of pairplot i can't find the option.

This is the df: This is the df

This is the part of the code:

sns.pairplot(data=dftrain,
              y_vars=['medv'],
              x_vars=dftrain.columns[:-1])

This is the plot: This is the plot

2

There are 2 best solutions below

2
On

The shape of a pairplot can't be changed. But, you can create a similar relplot if you convert the dataframe to long form.

Here is some simple example code, starting from dummy data:

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

df = pd.DataFrame(np.random.rand(300, 14), columns=[*"abcdefghijklmn"])
df_long = df.melt(id_vars=df.columns[-1], value_vars=df.columns[:-1])

g = sns.relplot(df_long, x=df.columns[-1], y='value', col='variable', col_wrap=4, height=2)

sns.relplot

0
On

You can use seaborn.FacetGrid and set a value of the parameter col_wrap.

col_wrap (int): “Wrap” the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet.

Try this :

cols= dftrain.columns[:-1].tolist()

g = sns.FacetGrid(pd.DataFrame(cols), col=0, col_wrap=3, sharex=False)

for ax, varx in zip(g.axes, cols):
    sns.scatterplot(data=dftrain, x=varx, y="medv", ax=ax)
    
g.tight_layout()

# Output :

enter image description here