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".
To annotate each cell of a heatmap, we can make annot = True in heatmap() method.
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.
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()
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With