Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position of Seaborn heatmap annotations in cells

The annotations in a Seaborn heatmap are centered in the middle of each cell by default. Is it possible to move the annotations to "top left".

like image 484
Pat Avatar asked Mar 29 '17 09:03

Pat


People also ask

How do you annotate a heatmap in Seaborn?

To annotate each cell of a heatmap, we can make annot = True in heatmap() method.

What is CMAP in heatmap?

You can customize the colors in your heatmap with the cmap parameter of the heatmap() function in seaborn. The following examples show the appearences of different sequential color palettes. # libraries import seaborn as sns import matplotlib.


1 Answers

A good idea may be to use the annotations from the heatmap, which are produces by the annot=True argument and later shift them half a pixel width upwards and half a pixel width left. In order for this shifted position to be the top left corner of the text itself, the ha and va keyword arguments need to set as annot_kws. The shift itself can be done using a translation transform.

import seaborn as sns
import numpy as np; np.random.seed(0)
import matplotlib.pylab as plt
import matplotlib.transforms

data = np.random.randint(100, size=(5,5))
akws = {"ha": 'left',"va": 'top'}
ax = sns.heatmap(data,  annot=True, annot_kws=akws)

for t in ax.texts:
    trans = t.get_transform()
    offs = matplotlib.transforms.ScaledTranslation(-0.48, 0.48,
                    matplotlib.transforms.IdentityTransform())
    t.set_transform( offs + trans )

plt.show()

enter image description here

The behaviour is a bit counterintuitive as +0.48 in the transform shifts the label upwards (against the direction of the axes). This behaviour seems to be corrected in seaborn version 0.8; for plots in seaborn 0.8 or higher use the more intuitive transform

offs = matplotlib.transforms.ScaledTranslation(-0.48, -0.48,
                    matplotlib.transforms.IdentityTransform())
like image 50
ImportanceOfBeingErnest Avatar answered Sep 19 '22 16:09

ImportanceOfBeingErnest