【发布时间】: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 看起来确实如此,而且我使用的是相同的包版本。
标签: python matplotlib seaborn heatmap