在 Seaborn 中向热图注释添加单位

Adding units to heatmap annotation in Seaborn

我正在尝试在 Seaborn 中显示 table 的百分比热图:

sns.heatmap(S, annot=True, fmt=".1f", linewidths=1.0, square=1)

但是,我希望百分号出现在热图注释中的每个数字之后。 fmt 标志似乎只接受数字格式说明符。有没有办法在 Seaborn 中或通过一些 matplotlib 调整来做到这一点?

您必须遍历热图的所有文本值并添加 % 符号:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from matplotlib.ticker import FuncFormatter

sns.set()
fig, ax0 = plt.subplots(1,1)
data = np.array([[10.01,20.20],[-0.23,0.],[23.1049,-100.000000]])
ax = sns.heatmap(data, annot=True, fmt = '.1f', square=1, linewidth=1.)
for t in ax.texts: t.set_text(t.get_text() + " %")
plt.show()

将“.1f”替换为“.1%”。它应该可以解决您的问题。

sns.heatmap(S, annot=True, fmt=".1%", linewidths=1.0, square=1)