seaborn heatmap with binary color coding and annotation of raw inputs

Viewed 534

enter image description here

I need to show the values in a dataframe column as a binary colormap, based on whether they are above or below a threshold. I also need to show the raw numbers.

I am using seaborn heatmap.

sample data frame

Month  Raw_value
Jan     3.72
feb     2.51
Mar     1.82
...

I have converted the column to binary, then retained only the index & binary column & removed other columns from dataframe, then plotted as binary. But this won't help to show the actual numbers (see figure).

kpi2['status'] = np.where(kpi2['raw_value'] > thres, 1,0) # convert to binary
kpi2 = kpi2.set_index('month')
kpi2.drop(['raw_value'], axis=1, inplace=True) # drop other columns
kpi_transposed = kpi2.transpose() # convert column to row for plotting horizontally
rdgn = sns.diverging_palette(h_neg=130, h_pos=10, s=99, l=55, sep=3, as_cmap=True)
sns.heatmap(kpi_transposed, linecolor='white', linewidths=1.3,vmin=0, vmax=1, cmap=rdgn, cbar=False)
plt.show()

But if I work with the raw data column, I am unsure how to color it as binary.

Any idea?

1 Answers

Instead of dropping raw_value. transpose both columns, then when calling the heatmap use loc to select the status as the data and pass raw_value to annot of sns.heatmap:

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

kpi2 = pd.DataFrame({'month': ['Jan', 'Feb', 'Mar'],
                     'raw_value': [3.72, 2.51, 1.82]})

thres = 3
kpi2['status'] = np.where(kpi2['raw_value'] > thres, 1, 0)
kpi2 = kpi2.set_index('month')

kpi_transposed = kpi2.transpose()

rdgn = sns.diverging_palette(h_neg=130, h_pos=10, s=99, l=55, sep=3,
                             as_cmap=True)

ax = sns.heatmap(
    kpi_transposed.loc[['status']],  # Select Status Column
    annot=kpi_transposed.loc[['raw_value']],  # Select raw_values for annot
    fmt='.2f',  # Specify Annotation Format
    linecolor='white', linewidths=1.3, vmin=0, vmax=1,
    cmap=rdgn, cbar=False
)

# Add Percent Sign
for t in ax.texts:
    t.set_text(t.get_text() + "%")
plt.show()

plot with annotations

Related