具有相同像元大小的Seaborn相关热图 [英] Seaborn correlation heatmap with equal cell size

查看:53
本文介绍了具有相同像元大小的Seaborn相关热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

哪个会产生:

但是我想拥有:

推荐答案

您可以获取 ax 的边界框,并根据需要的缩放比例重新放置它的位置:

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

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

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

这篇关于具有相同像元大小的Seaborn相关热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆