Brian Keegan
Brian Keegan

Reputation: 2229

Reshape subplots on a Seaborn PairGrid

I really like the functionality of Seaborn's PairGrid. However, I haven't been able to reshape the subplots to my satisfaction. For instance, the code below will return a figure with 1 column and 2 rows, reflecting the 1 x-variable and 2 y-variables.

import seaborn as sns
tips = sns.load_dataset('tips')
g = sns.PairGrid(tips,y_vars=['tip','total_bill'],x_vars=['size'], hue='sex')
g.map(sns.regplot,x_jitter=.125)

enter image description here

However, it would be much preferable for me to re-orient this figure to have 2 columns and 1 row. It appears these subplots live within g.axes, but how do I pass them back to a plt.subplots(1,2) type of function?

Upvotes: 1

Views: 2639

Answers (1)

hitzg
hitzg

Reputation: 12711

PairGrid chooses this alignment because both plots have the same x axis. So the simplest way to get the plots in landscape would be to swap x and y:

import seaborn as sns
tips = sns.load_dataset('tips')
g = sns.PairGrid(tips,x_vars=['tip','total_bill'],y_vars=['size'], hue='sex')
g.map(sns.regplot,y_jitter=.125)

(Note that you also have to change x_jitter to y_jitter to get the same result.)

If you don't want to do that, then I think PairGrid is not the right tool for you. You can also just use two subplots and create the plots using sns.regplot:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset('tips')
male = tips[tips.sex=='Male']
female = tips[tips.sex=='Female']

with sns.color_palette(n_colors=2):
    fig, axs = plt.subplots(1,2)
    sns.regplot(x='size', y='tip', data=male, x_jitter=.125, ax=axs[0])
    sns.regplot(x='size', y='tip', data=female, x_jitter=.125, ax=axs[0])
    sns.regplot(x='size', y='total_bill', data=male, x_jitter=.125, ax=axs[1])
    sns.regplot(x='size', y='total_bill', data=female, x_jitter=.125, ax=axs[1])

Upvotes: 5

Related Questions