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

Seaborn Heatmap correlation won't fit annotation digits

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

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

我已经尝试更改无花果大小,但没有帮助。还尝试使用 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")

我将此处的标签替换为与实际标签大小相同的占位符。

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

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

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

正如评论中指出的那样,使用 square=Falsefigsize=(30, 15) 解决了问题。