英文:
How to add custom annotations with uncertainty to a heatmap
问题
I'm here to provide the translated content as requested:
我正试图将一些数据可视化为表格,其中每个表格元素的框根据其值着色,还显示数值值,并显示每个元素的不确定性。我可以使用 pandas.pivot_table
和 sns.heatmap
实现这三个事情中的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
数组,因此对每个元素进行字符串格式化对此无效。
英文:
I am attempting to visualize some data as a table, where the boxes of each table element are colored according to their value, the numerical value is also displayed, and the uncertainty on each element is shown. I can achieve 2 out of these 3 things using pandas.pivot_table
and sns.heatmap
, but cannot seem to include the uncertainty on each table element as part of the annotation. In the example code snippet:
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)
we produce a table like so:
However, imagine that the entries "E"
represented the uncertainty on elements "D"
. Is there any way these can be displayed on the table, as "E"[i]+/-"D"[i]
? I tried using a custom annotation grid, but this requires a numpy
array and so string formatting each element didn't work for this.
答案1
得分: 4
你可以将格式化字符串的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='')
英文:
You can pass a DataFrame with the formatted strings to 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='')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论