简体   繁体   English

如何在matplotlib中用文本注释热图

[英]how to annotate heatmap with text in matplotlib

I am plotting a heatmap in matplotlib using:我正在使用以下命令在 matplotlib 中绘制热图:

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 .这意味着在绘制的热图的每个单元格中,将与该单元格对应的值放入传递给pcolor的 5x5 矩阵中。 thanks.谢谢。

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

代码输出

HTH HTH

The seaborn heatmap does the job automatically, by setting annot=True . seaborn 热图通过设置annot=True自动完成工作。

See this for an example.请参阅示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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