具有相同像元大小的Seaborn相关热图

时间:2020-10-02 15:08:55

标签: python pandas matplotlib seaborn correlation

我正在使用seaborn绘制具有不同列数的各种相关矩阵。 为了使人眼花can乱,我想让所有相关矩阵都具有相同的像元大小。 不幸的是,我无法参数化seaborn的参数。 这是一个最小的示例:

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

哪个会产生:

actual image

但是我想拥有:

desired image

1 个答案:

答案 0 :(得分:1)

您可以获取ax的边界框,并使用所需的比例因子将其重新放置:

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

下面是一个具有2至6列相关性的示例:

between 2 and 6 columns