Mitchell van Zuylen
Mitchell van Zuylen

Reputation: 4125

Make cells have the same size between seaborn heatmaps

I am making two seaborn heatmaps, which I am putting into two matplotlib subplots, like so:

fig, axes = plt.subplots(2, 1, sharex=True, figsize=(5,10))


data = [
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
]
sns.heatmap(
        data, 
        ax=axes[0],
        linewidths=0.2,
        cbar=False)


data = [
    [0,0,0],
    [0,0,0],
    [0,0,0],
]
sns.heatmap(
        data, 
        ax=axes[1],
        linewidths=0.2,
        cbar=False)

axes[0].set_title("A")
axes[1].set_title('B')

enter image description here

As you can see, this results in subplot A and B. The individual cells within subplot A are all the same size. The cells within subplot B are also all the same size. However, the cells between A and B are different sizes. How can I make sure that the size of cells between the subplots are the same?

I understand that means that plot A would overall be larger then plot B, which is not an issue.

Upvotes: 2

Views: 1154

Answers (1)

Mitchell van Zuylen
Mitchell van Zuylen

Reputation: 4125

A possible solution is to change the size ratio of the two subplots.

If the size ratio between plot A and B is set to be the same as the ratio between the number of rows for plot A and B, the size should be (more or less) the same.

data_a = [
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
]
data_b = [
    [0,0,0],
    [0,0,0],
    [0,0,0],
]
fig, axes = plt.subplots(2, 1, 
        sharex=True, 
        figsize=(5,10), 
        gridspec_kw={'height_ratios': [len(data_a), len(data_b)]})


sns.heatmap(
        data_a, 
        ax=axes[0],
        linewidths=0.2,
        cbar=False)

sns.heatmap(
        data_b, 
        ax=axes[1],
        linewidths=0.2,
        cbar=False)

axes[0].set_title("A")
axes[1].set_title('B')

enter image description here

I am wondering if there is also a seaborn option that can be toggled to get this behavior?

Upvotes: 2

Related Questions