Seaborn correlation heatmap with equal cell size

夙愿已清 提交于 2021-02-10 16:18:08

问题


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:

But I'd like to have:


回答1:


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()

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



来源:https://stackoverflow.com/questions/64173951/seaborn-correlation-heatmap-with-equal-cell-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!