Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python Seaborn热图中添加文本加值_Python_Python 2.7_Python 3.x - Fatal编程技术网

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

如何在Python Seaborn热图中添加文本加值,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我正在尝试python Seaborn包来创建热图。 到目前为止,我已经能够创建热图中的值。 我在创建热图的代码中的最后一行是: sns.heatmap(result, annot=True, fmt='.2f', cmap='RdYlGn', ax=ax) 生成的图像如下所示: 但是,我希望在值旁边还有一个字符串。 例如:AAPL-1.25,而不是第二行第二个字段中的-1.25。有没有办法将文本添加到热图中的值?您可以使用seaborn向热图添加自定义注释。原则上,这只是一种特殊情况。现在

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

sns.heatmap(result, annot=True, fmt='.2f', cmap='RdYlGn', ax=ax)
生成的图像如下所示:

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

您可以使用seaborn向热图添加自定义注释。原则上,这只是一种特殊情况。现在的想法是将字符串和数字相加,以获得适当的自定义标签。如果您有一个与
结果
形状相同的数组
字符串
,其中包含相应的标签,则可以使用以下方法将它们添加到一起:

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()
结果如下所示:

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

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