如何在Python Seaborn Heatmap中添加文本加值

How to Add Text plus Value in Python Seaborn Heatmap

我正在尝试使用Python Seaborn软件包创建热图。
到目前为止,我已经能够使用其中的值创建热图。
我在创建热图的代码中的最后一行是:

1
sns.heatmap(result, annot=True, fmt='.2f', cmap='RdYlGn', ax=ax)

结果图像如下所示:
Heatmap with Values

但是,我想在值旁边也有一个字符串。
例如:AAPL -1.25代替第二行第二个字段中的-1.25。 有没有一种方法可以将文本添加到热图中的值?


您可以使用seaborn将自定义注释添加到您的热图。 原则上,这只是此答案的特例。 现在的想法是将字符串和数字加在一起以获得适当的自定义标签。 如果具有与result相同形状的数组strings,其中包含各个标签,则可以使用以下命令将它们添加在一起:

1
2
3
4
labels = (np.asarray(["{0} {1:.3f}".format(string, value)
                      for string, value in zip(strings.flatten(),
                                               results.flatten())])
         ).reshape(3, 4)

现在,您可以将此标签数组用作热图的自定义标签:

1
sns.heatmap(result, annot=labels, fmt="", cmap='RdYlGn', ax=ax)

如果使用一些随机输入数据将它们放在一起,则代码将如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

results = np.random.rand(4, 3)
strings = strings = np.asarray([['a', 'b', 'c'],
                                ['d', 'e', 'f'],
                                ['g', 'h', 'i'],
                                ['j', 'k', 'l']])

labels = (np.asarray(["{0} {1:.3f}".format(string, value)
                      for string, value in zip(strings.flatten(),
                                               results.flatten())])
         ).reshape(4, 3)

fig, ax = plt.subplots()
sns.heatmap(results, annot=labels, fmt="", cmap='RdYlGn', ax=ax)
plt.show()

结果将如下所示:

enter image description here

如您所见,字符串现在已正确添加到注释中的值。