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

Mil*_*ind 5 python python-2.7 python-3.x

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

sns.heatmap(result, annot=True, fmt='.2f', cmap='RdYlGn', ax=ax)
Run Code Online (Sandbox Code Playgroud)

生成的图像如下所示: 带有值的热图

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

jot*_*asi 8

您可以使用 seaborn 向热图添加自定义注释。原则上,这只是这个答案的一个特例。现在的想法是将字符串和数字相加以获得正确的自定义标签。如果您有一个stringsresult包含相应标签的形状相同的数组,您可以使用以下方法将它们添加在一起:

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

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

sns.heatmap(result, annot=labels, fmt="", cmap='RdYlGn', ax=ax)
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

结果将如下所示:

在此处输入图片说明

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