Masking annotations in seaborn heatmap

夙愿已清 提交于 2020-05-17 03:51:08

问题


I would like to make a heatmap that has annotation only in specific cells. I though one way to do this would be to make a heatmap with annotations in all cells and then overlay another heatmap that has no annotation but that is masked in the regions that I want the original annotations to be visible:

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)

However, this is not working - the second heatmap is not covering up the first one:

Please advise


回答1:


I tried a few things, including using numpy.nan or "" in the annot array. Unfortunately they don't work.

This is probably the easiest way. It involves grabbing the texts of the axes, which should only be the labels in annot which sns.heatmap puts there.

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



来源:https://stackoverflow.com/questions/52017735/masking-annotations-in-seaborn-heatmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!