如何在Python Seaborn热图中添加文本加值

2024-05-17 19:44:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试python Seaborn包来创建热图。 到目前为止,我已经能够创建包含值的热图。 我在创建热图的代码中的最后一行是:

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

生成的图像如下所示: Heatmap with Values

但是,我希望在值旁边还有一个字符串。 例如:AAPL-1.25而不是第二行第二个字段中的-1.25。有没有办法将文本添加到热图中的值?在


Tags: 字符串代码图像trueresultseabornaxcmap
1条回答
网友
1楼 · 发布于 2024-05-17 19:44:52

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

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

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

^{pr2}$

如果使用一些随机输入数据将其组合在一起,代码将如下所示:

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

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

相关问题 更多 >