Write values in heatmap-like plot, but for categorical variables in seaborn

Viewed 545

I plot a dataframe in a heatmap-like plot, and I would like to write to the cell, but not the value of the cell but I compare the value with conditions and tells which kind of error it is.

For example:

import pandas as pd 
import seaborn as sns # matplotlib inline 
import random
data = []
for i in range(10):
    data.append([random.randrange(0, 11, 1) for _ in range(10)])
df = pd.DataFrame(data)
n = 10

fig, ax = plt.subplots(figsize = (12, 10)) 
cmap = ['#b3e6b3','#66cc66','#2d862d','#ffc299','#ff944d','#ff6600','#ccddff','#99bbff','#4d88ff','#0044cc','#002b80']
ax = sns.heatmap(df, cmap=cmap, linewidths = 0.005, annot = False) 
                            
plt.show()

What I got when running this code is:

this is without values

Then I compare dataframe df with some conditions and get 2 other dataframes, for example:

condition1 = [['Error A'] + [np.nan]*9,
            [np.nan]*6 + ['Error C'] + [np.nan]*3,
            [np.nan]*10,
            [np.nan]*7 + ['Error B'] + [np.nan]*2,
            [np.nan]*2 + ['Error D'] + [np.nan]*3 + ['Error B'] + [np.nan]*3,
            [np.nan]*10,
            [np.nan]*3 + ['Error B'] + [np.nan]*6,
            [np.nan]*7 + ['Error A'] + [np.nan]*2,
            [np.nan]*10,
            [np.nan]*10]
df_condition1 = pd.DataFrame(data = condition1)

condition2 = [[np.nan]*10,[np.nan]*10,
            [np.nan]*10,[np.nan]*7 + ['Error C'] + [np.nan]*2,
            [np.nan]*10,[np.nan]*10,[np.nan]*10,
            [np.nan]*10,
            [np.nan]*10,
            [np.nan]*10]
df_condition2 = pd.DataFrame(data = condition2)

and what I want is to show values of these dataframes in the heatmap, like this:

what I want

How can I do it?

1 Answers

You can build the error texts and annotate manually:

c1, c2 = df_condition1.notna(), df_condition2.notna()
df_condition1,df_condition2 = df_condition1.fillna(''), df_condition2.fillna('')

errors = np.select((c1&c2, c1, c2), 
                   (df_condition1+'\n'+df_condition2, df_condition1, df_condition2),
                   '')

fig, ax = plt.subplots(figsize = (12, 10)) 
cmap = ['#b3e6b3','#66cc66','#2d862d','#ffc299','#ff944d','#ff6600','#ccddff','#99bbff','#4d88ff','#0044cc','#002b80']
ax = sns.heatmap(df, cmap=cmap, linewidths = 0.005, annot = False) 
    
for r in range(errors.shape[0]):
    for c in range(errors.shape[1]):
        ax.text(c+0.5,r+0.5, errors[r,c], 
                va='center',ha='center',
                fontweight='bold')


plt.show()

Output:

enter image description here

Related