pandas 如何向热图添加具有不确定性的自定义注解

p1tboqfb  于 2023-05-21  发布在  其他
关注(0)|答案(1)|浏览(97)

我试图将一些数据可视化为一个表格,其中每个表格元素的框根据其值进行着色,还显示数值,并显示每个元素的不确定性。我可以使用pandas.pivot_tablesns.heatmap实现这3件事中的2件,但似乎不能将每个表元素上的不确定性作为注解的一部分。在示例代码段中:

import pandas as pd
import seaborn as sns
import numpy as np

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar"],
                   "B": ["one", "one", "one", "two", "two",
                         "one", "one", "two", "two"],
                   "C": ["small", "large", "large", "small",
                         "small", "large", "small", "small",
                         "large"],
                   "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                   "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})

table = pd.pivot_table(df, values='D', index=['A', 'B'],
                       columns=['C'], aggfunc=np.sum, fill_value=0)

sns.heatmap(table,annot=True)

我们生成一个这样的表:

然而,假设条目"E"表示元素"D"上的不确定性。有没有什么方法可以在表上显示这些,如"E"[i]+/-"D"[i]?我尝试使用自定义注解网格,但这需要一个numpy数组,因此对每个元素进行字符串格式设置不适用。

fwzugrvs

fwzugrvs1#

您可以将带有格式化字符串的DataFrame传递给sns.heatmap

table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'B'],
                       columns=['C'], aggfunc=np.sum, fill_value=0)

sns.heatmap(table['D'],
            annot=table['D'].astype(str)+'±'+table['E'].astype(str),
            fmt='')

相关问题