如何将相关热图限制为感兴趣的单元格并添加星标以标记特殊值?

How to restrict a correlation heatmap to interesting cells and add stars to mark exceptional values?

我正在尝试在 python 中制作一个漂亮的相关矩阵热图,但我找不到按我想要的方式自定义它的选项。

我的代码就是这个:

plt.figure(figsize=(16, 6))
mask = np.triu(np.ones_like(Correlazioni.corr(), dtype=np.bool))
heatmap = sns.heatmap(Correlazioni.corr(), mask=mask, vmin=-1, vmax=1, annot=True, cmap='BrBG')
heatmap.set_title('Triangle Correlation Heatmap', fontdict={'fontsize':18}, pad=16);

现在我想在重要的单元格中添加(*):(例如:当系数高于或低于某个值时)

非常感谢您的回答,如果我的请求中有任何遗漏,请告诉我,我会提供。

要显示较少的单元格,您可以扩展遮罩,遮掉不需要的值。 除了设置 annot=True,还可以提供字符串列表。您可以完全控制如何格式化这些字符串,例如添加星星:

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

np.random.seed(124)
Correlazioni = pd.DataFrame(np.random.rand(7, 10), columns=[*'abcdefghij'])

plt.figure(figsize=(16, 6))
corr = Correlazioni.corr()
mask = np.triu(np.ones_like(corr, dtype=np.bool))
cut_off = 0.6  # only show cells with abs(correlation) at least this value
extreme_1 = 0.75  # show with a star
extreme_2 = 0.85  # show with a second star
extreme_3 = 0.90  # show with a third star
mask |= np.abs(corr) < cut_off
corr = corr[~mask]  # fill in NaN in the non-desired cells

remove_empty_rows_and_cols = True
if remove_empty_rows_and_cols:
    wanted_cols = np.flatnonzero(np.count_nonzero(~mask, axis=1))
    wanted_rows = np.flatnonzero(np.count_nonzero(~mask, axis=0))
    corr = corr.iloc[wanted_cols, wanted_rows]

annot = [[f"{val:.4f}"
          + ('' if abs(val) < extreme_1 else '\n★')  # add one star if abs(val) >= extreme_1
          + ('' if abs(val) < extreme_2 else '★')  # add an extra star if abs(val) >= extreme_2
          + ('' if abs(val) < extreme_3 else '★')  # add yet an extra star if abs(val) >= extreme_3
          for val in row] for row in corr.to_numpy()]
heatmap = sns.heatmap(corr, vmin=-1, vmax=1, annot=annot, fmt='', cmap='BrBG')
heatmap.set_title('Triangle Correlation Heatmap', fontdict={'fontsize': 18}, pad=16)
plt.show()

下面是删除空行和空列后的样子。请注意,它看起来不再是完美的三角形了。