简体   繁体   中英

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".

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())

You can use annot_kws of seaborn and set vertical (va) and horizontal (ha) alignments like here (sometimes it works bad):

...
annot_kws = {"ha": 'left',"va": 'top'}
ax = sns.heatmap(data, annot=True, annot_kws=annot_kws)
...

在此处输入图片说明

Another way put labels manually like here:

import seaborn as sns
import numpy as np
import matplotlib.pylab as plt

data = np.random.randint(100, size=(5,5))
ax = sns.heatmap(data)

# put labels manually
for y in range(data.shape[0]):
    for x in range(data.shape[1]):
        plt.text(x, y+1, '%d' % data[data.shape[0] - y - 1, x],
         ha='left',va='top', color='r')
plt.show()

在此处输入图片说明

For more information and to understand text layout (why 1st example works bad?) in matplotlib read this topic: http://matplotlib.org/users/text_props.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM