遮盖seaborn热图中的注释

时间:2018-08-25 13:21:07

标签: python-3.x matplotlib seaborn

我想制作仅在特定单元格中具有注释的热图。我执行此操作的一种方法是在所有单元格中制作带有注释的热图,然后覆盖另一个没有注释但在希望原始注释可见的区域中被屏蔽的热图:

import numpy as np
import seaborn as sns

par_corr_p = np.array([[1, 2], [3, 4]])
masked_array = np.ma.array(par_corr_p, mask=par_corr_p<2)

fig, ax = plt.subplots()
sns.heatmap(par_corr_p, ax=ax, cmap ='RdBu_r', annot = par_corr_p, center=0, vmin=-5, vmax=5)
sns.heatmap(par_corr_p, mask = masked_array.mask, ax=ax,  cmap ='RdBu_r', center=0, vmin=-5, vmax=5)

但是,这不起作用-第二个热图没有覆盖第一个热图:

enter image description here

请告知

1 个答案:

答案 0 :(得分:0)

我尝试了一些方法,包括在annot数组中使用numpy.nan或“”。不幸的是,它们不起作用。

这可能是最简单的方法。它涉及到抓取texts的轴,这些轴只能是annot放在其中的sns.heatmap中的标签。

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

par_corr_p = np.array([[1, 2], [3, 4]])

data = par_corr_p
show_annot_array = data >= 2

fig, ax = plt.subplots()
sns.heatmap(
    ax=ax,
    data=data,
    annot=data,
    cmap ='RdBu_r', center=0, vmin=-5, vmax=5
)
for text, show_annot in zip(ax.texts, (element for row in show_annot_array for element in row)):
    text.set_visible(show_annot)

plt.show()

enter image description here