2

I'm trying to make a function that produces two pairplots side by side. I've got it to produce 1 at time.

import seaborn as sns
data = sns.load_dataset("iris")

def pairplot(col,hue_var):
    sns.set(style="ticks")
    cols_to_look_at = col + [hue_var]
    sns.pairplot(data[cols_to_look_at], hue=hue_var)

col_names1 =  ['sepal_length', 'sepal_width']
col_names2 =  ['petal_length', 'petal_width']

pairplot(col_names1,'species')
pairplot(col_names2,'species')

grateful for any help

HarriS
  • 605
  • 1
  • 6
  • 19

1 Answers1

2

In fact it is not a trivial matter.

pairplot has not ax parameter to make it simple due to its nature of "figure-level" at seaborn.

There are some hacks: How to plot multiple Seaborn Jointplot in Subplot

A "clean" one consists in saving the plots as images to bring them back to place them: https://stackoverflow.com/a/61330067/10372616

Using it in your plots:

import matplotlib.image as mpimg
import matplotlib.pyplot as plt


import seaborn as sns
data = sns.load_dataset("iris")


def pairplot(col,hue_var):

    sns.set(style="ticks")
    cols_to_look_at = col + [hue_var] 
    return sns.pairplot(data[cols_to_look_at], hue=hue_var) # !!! I've placed a return

col_names1 =  ['sepal_length', 'sepal_width']
col_names2 =  ['petal_length', 'petal_width']

g0 = pairplot(col_names1,'species')
g1 = pairplot(col_names2,'species')



############### 1. SAVE PLOTS IN MEMORY TEMPORALLY
g0.savefig('g0.png', dpi=300)
plt.close(g0.fig)

g1.savefig('g1.png', dpi=300)
plt.close(g1.fig)


############### 2. CREATE YOUR SUBPLOTS FROM TEMPORAL IMAGES
f, axarr = plt.subplots(1, 2, figsize=(20, 20))

axarr[0].imshow(mpimg.imread('g0.png'))
axarr[1].imshow(mpimg.imread('g1.png'))

# turn off x and y axis
[ax.set_axis_off() for ax in axarr.ravel()]

plt.tight_layout()
plt.show()
Marcos
  • 786
  • 7
  • 8