Example of how to add text (units, %, etc) in a heatmap cell annotations using seaborn in python:
1 -- Create a simple heatmap with seaborn
Let's create a heatmap with seaborn:
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = np.array([[25.55535942, 1.99598017, 9.78107706],
[ 4.95758736, 39.68268716, 16.78109873],
[ 0.45401194, 0.10003128, 0.6921669 ]])
df = pd.DataFrame(data=data)
fig = plt.figure(num=None, figsize=(10, 10), dpi=80, facecolor='w', edgecolor='k')
cmap = sns.cubehelix_palette(light=1, as_cmap=True)
res = sns.heatmap(df, annot=True, vmin=0.0, vmax=100.0,
fmt='.2f', cmap=cmap, cbar_kws={"shrink": .82},
linewidths=0.1, linecolor='gray')
res.invert_yaxis()
plt.title('Seaborn heatmap - add ')
plt.show()
2 -- Add text to the annotations
To add text (for example here the symbol percentage %), a solution is to do:
for t in res.texts: t.set_text(t.get_text() + " %")
Source code
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = np.array([[25.55535942, 1.99598017, 9.78107706],
[ 4.95758736, 39.68268716, 16.78109873],
[ 0.45401194, 0.10003128, 0.6921669 ]])
df = pd.DataFrame(data=data)
fig = plt.figure(num=None, figsize=(10, 10), dpi=80, facecolor='w', edgecolor='k')
cmap = sns.cubehelix_palette(light=1, as_cmap=True)
res = sns.heatmap(df, annot=True, vmin=0.0, vmax=100.0,
fmt='.2f', cmap=cmap, cbar_kws={"shrink": .82},
linewidths=0.1, linecolor='gray')
res.invert_yaxis()
for t in res.texts: t.set_text(t.get_text() + " %")
plt.title('Seaborn heatmap - add ')
plt.savefig('seaborn_heatmap_with_frame_and_cell_border_01.png')
plt.show()
returns
3 -- Annotations customization
Another solution is to custom the annotations:
labels = np.array([['A','B','C'],['D','E','F'],['G','H','I']])
and edit the heatmap() function, like this:
annot=labels et fmt=''
Source code
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = np.array([[25.55535942, 1.99598017, 9.78107706],
[ 4.95758736, 39.68268716, 16.78109873],
[ 0.45401194, 0.10003128, 0.6921669 ]])
df = pd.DataFrame(data=data)
fig = plt.figure(num=None, figsize=(10, 10), dpi=80, facecolor='w', edgecolor='k')
cmap = sns.cubehelix_palette(light=1, as_cmap=True)
labels = np.array([['A','B','C'],['D','E','F'],['G','H','I']])
res = sns.heatmap(df, annot=labels, vmin=0.0, vmax=100.0,
fmt='', cmap=cmap, cbar_kws={"shrink": .82},
linewidths=0.1, linecolor='gray')
res.invert_yaxis()
#for t in res.texts: t.set_text(t.get_text() + " %")
plt.savefig('seaborn_heatmap_add_annotation_02.png')
plt.show()
returns