how to annotate heatmap with text in matplotlib?


Question

I am plotting a heatmap in matplotlib using:

plt.pcolor(rand(5,5))

how can I annotate the heatmap with the actual numbers plotted? meaning in each cell of the plotted heatmap, put the value corresponding to that cell in the 5x5 matrix passed to pcolor. thanks.

1
25
8/11/2012 8:48:47 PM

Accepted Answer

There is no automatic feature to do such a thing, but you could loop through each point and put text in the appropriate location:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(5, 4)
heatmap = plt.pcolor(data)

for y in range(data.shape[0]):
    for x in range(data.shape[1]):
        plt.text(x + 0.5, y + 0.5, '%.4f' % data[y, x],
                 horizontalalignment='center',
                 verticalalignment='center',
                 )

plt.colorbar(heatmap)

plt.show()

Code output

HTH

45
8/11/2012 10:18:15 PM

The seaborn heatmap does the job automatically, by setting annot=True.

See this for an example.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon