seaborn.heatmap in subplots with equal cell sizes

Question:

I am plotting various correlation matrices with a different number of columns using seaborn.
For the sake of eye-candy, I’d like to have all correlation matrices to have the same cell size.
Unfortunately, I am not able to parameterize seaborn to do so.
Here is a minimal example:

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

# Generate two random dataset
rs = np.random.RandomState(42)
d1 = pd.DataFrame(data=rs.normal(size=(100, 2)), columns=list(ascii_letters[:2]))
d2 = pd.DataFrame(data=rs.normal(size=(100, 4)), columns=list(ascii_letters[:4]))

f, ax = plt.subplots(1,2,figsize=(6, 6))
# Draw the heatmap
sns.heatmap(d1.corr(), vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}, ax=ax[0])
sns.heatmap(d2.corr(), vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}, ax=ax[1])
f.show()

Which produces:

actual image

But I’d like to have:

desired image

Asked By: Tik0

||

Answers:

You can fetch the bounding box of the ax and reposition it with desired the scaling factor:

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

# Generate two random dataset
rs = np.random.RandomState(42)
d1 = pd.DataFrame(data=rs.normal(size=(100, 2)), columns=list(ascii_letters[:2]))
d2 = pd.DataFrame(data=rs.normal(size=(100, 4)), columns=list(ascii_letters[:4]))

fig, axes = plt.subplots(1, 2, figsize=(6, 6))
# Draw the heatmap
sns.heatmap(d1.corr(), vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}, ax=axes[0])
sns.heatmap(d2.corr(), vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}, ax=axes[1])

dfs = [d1, d2]
max_cols = max([len(df.columns) for df in dfs])
for ax, df in zip(axes, dfs):
    len_col = len(df.columns)
    if len_col < max_cols:
        fac = len_col / max_cols
        bbox = ax.get_position()
        ax.set_position([bbox.x0 + (1 - fac) / 2 * bbox.width, bbox.y0 + (1 - fac) / 2 * bbox.height,
                         fac * bbox.width, fac * bbox.height])
fig.show()

resulting plot

Here is an example with correlations from 2 to 6 columns:

between 2 and 6 columns

Answered By: JohanC