gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:31:36 37 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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

现在,您可以将此标签数组用作热图的自定义标签:
sns.heatmap(result, annot=labels, fmt="", cmap='RdYlGn', ax=ax)

如果您使用一些随机输入数据将它们放在一起,代码将如下所示:
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

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

关于python - 如何在 Python Seaborn Heatmap 中添加文本加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41164710/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com