Seaborn 热图相关性不适合注释数字

Posted

技术标签:

【中文标题】Seaborn 热图相关性不适合注释数字【英文标题】:Seaborn Heatmap correlation won't fit annotation digits 【发布时间】:2021-12-23 01:54:37 【问题描述】:

我正在尝试使用 seaborn 热图绘制三角相关矩阵,但单元格不适合注释数字。

知道如何让它们很好地适应各自的热图单元格吗?

我已经尝试过更改 figsize 并且没有帮助。还尝试使用 square=False。

我正在使用 seaborn==0.11.2 和 matplotlib==3.4.3

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Generate a dummy df
df = pd.DataFrame(np.random.rand(44,44))

label_lens = [16, 16, 16, 16, 16, 16, 16, 16, 20, 11,
              9, 10, 10, 16, 16, 16, 16, 12, 45, 10, 10,
             10, 10, 10, 10, 10, 10, 12, 12, 50, 50, 50,
             50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]

col_labels = []
for label_len in label_lens:
    col_labels.append('X'*label_len)

df.columns = col_labels

# Build correlation matrix df
correlation_matrix = df.corr()

# Get Diagonal Mask. Square matrix is not relevant.
mask = np.triu(np.ones_like(correlation_matrix, dtype=bool))

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(30, 15))

# Draw the heatmap with the mask and correct aspect ratio
sns_plot = sns.heatmap(correlation_matrix,
                       mask=mask,
                       annot=True,
                       fmt='.2f',
                       square=True)
f.set_tight_layout(True)
f.savefig("my_corr_matrix.pdf")

我在这里用与实际标签大小相同的占位符替换了我的标签。

【问题讨论】:

增加图形大小f, ax = plt.subplots(figsize=(30, 20)) 并删除square=True 适用于样本数据,但您的刻度标签较长,因此您可能需要大于 30 我尝试了 figsize=(90, 60)。没有运气。图变得很大,但注释仍然不合适。 Plot Image我可以重现您的问题。 @TrentonMcKinney,请查看更新后的代码。现在您可以使用虚拟标签进行复制了。 plot sample 看起来确实如此,而且我使用的是相同的包版本。 【参考方案1】:

正如 cmets 中所指出的,使用 square=Falsefigsize=(30, 15) 解决了问题。

【讨论】:

【参考方案2】:

问题是您的标签占用了 jupyter 最大宽度的太多空间。根据这个答案,您可能有 2 个选项,第一个 is editing jupyter width

https://***.com/a/34058270/2970272

第二个将是lowering how much you're using the plot space,通过修剪标签、降低字体、移除颜色条等。从下面的代码中检查所有“## HERE”cmets 以轻松找到我所做的更改。

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Generate a dummy df
df = pd.DataFrame(np.random.rand(44,44))

label_lens = [16, 16, 16, 16, 16, 16, 16, 16, 20, 11,
              9, 10, 10, 16, 16, 16, 16, 12, 45, 10, 10,
             10, 10, 10, 10, 10, 10, 12, 12, 50, 50, 50,
             50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]
#label_lens= [5]*len(label_lens)

col_labels = []
for label_len in label_lens:
    col_labels.append(f"'X'*label_len"[:10]) ## HERE -- max char limit

df.columns = col_labels

# Build correlation matrix df
correlation_matrix = df.corr()

# Get Diagonal Mask. Square matrix is not relevant.
mask = np.triu(np.ones_like(correlation_matrix, dtype=bool))

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(30, 20)) ## here increased figsize

## HERE - max tick font size
ax.tick_params(axis='both', labelsize=8)

# Draw the heatmap with the mask and correct aspect ratio
sns_plot = sns.heatmap(correlation_matrix,
                       mask=mask,
                       annot=True,
                       fmt='.2f',
                       square=True,
                       cbar=False) ## HERE removed colorbar
f.set_tight_layout(True)
## HERE - rotating ticks to give more space
plt.setp(ax.yaxis.get_majorticklabels(), rotation=-45)
plt.setp(ax.xaxis.get_majorticklabels(), rotation=-45)
plt.show()
#f.savefig("my_corr_matrix.pdf")

【讨论】:

试过了。没有运气。标签到处都是,包括 cbar 下方。 @MatheusTorquato,我编辑了我的答案,采用了与 square=False 不同的方法,不会限制数据。

以上是关于Seaborn 热图相关性不适合注释数字的主要内容,如果未能解决你的问题,请参考以下文章

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

使用 python seaborn 仅在某些值之间设置热图相关性

具有二进制颜色编码和原始输入注释的 seaborn 热图

如何为 seaborn 的热图或相关矩阵设置动画?

在 Seaborn 中将相关矩阵绘制为热图时,是不是可以删除重复的列/行?

自定义注释 Seaborn 热图