【问题标题】:Seaborn correlation heatmap with equal cell size具有相同单元大小的 Seaborn 相关热图
【发布时间】:2021-01-18 06:32:38
【问题描述】:

我正在使用 seaborn 绘制具有不同列数的各种相关矩阵。 为了吸引眼球,我希望所有相关矩阵都具有相同的单元格大小。 不幸的是,我无法通过参数化 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()

产生:

但我想要:

【问题讨论】:

    标签: python pandas matplotlib seaborn correlation


    【解决方案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()
    

    以下是 2 到 6 列相关性的示例:

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      相关资源
      最近更新 更多