johntan05 johntan05 - 1 month ago 40
Python Question

GridSpec on Seaborn Subplots

I currently have 2 subplots using seaborn:

import matplotlib.pyplot as plt
import seaborn.apionly as sns

f, (ax1, ax2) = plt.subplots(2, sharex=True)

sns.distplot(df['Difference'].values, ax=ax1) #array, top subplot

sns.boxplot(df['Difference'].values, ax=ax2, width=.4) #bottom subplot
sns.stripplot([cimin, cimax], color='r', marker='d') #overlay confidence intervals over boxplot

ax1.set_ylabel('Relative Frequency') #label only the top subplot

plt.xlabel('Difference')

plt.show()


Here is the output:

Distribution Plot

I am rather stumped on how to make ax2 (the bottom figure) to become shorter relative to ax1 (the top figure). I was looking over the GridSpec (http://matplotlib.org/users/gridspec.html) documentation but I can't figure out how to apply it to seaborn objects.

Question:


  1. How do I make the bottom subplot shorter compared to the top
    subplot?

  2. Incidentally, how do I move the plot's title "Distrubition of Difference" to go above the top
    subplot?



Thank you for your time.

Answer

As @dnalow mentioned, seaborn has no impact on GridSpec, as you pass a reference to the Axes object to the function. Like so:

import matplotlib.pyplot as plt
import seaborn.apionly as sns
import matplotlib.gridspec as gridspec

tips = sns.load_dataset("tips")

gridkw = dict(height_ratios=[5, 1])
fig, (ax1, ax2) = plt.subplots(2, 1, gridspec_kw=gridkw)

sns.distplot(tips.loc[:,'total_bill'], ax=ax1) #array, top subplot
sns.boxplot(tips.loc[:,'total_bill'], ax=ax2, width=.4) #bottom subplot

plt.show()

enter image description here

Comments