在Seaborn中为热力图注释添加单位

24

我正在尝试在Seaborn中将百分比表格显示为热度图:

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

不过,我希望在热图注释中每个数字后面都能出现百分号。 fmt 标志似乎只接受数字格式说明符。是否有一种方法可以在 Seaborn 中或通过一些 matplotlib 调整来实现这一点?

3个回答

38
您需要迭代热图的所有文本值并添加百分号:%。
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()

enter image description here


我想在注释中添加百分号(例如您的图中的0.23%),而不是在色条上添加。 - Jsl
4
将 '.1f' 转换为 '.1%' 解决了我的问题。 - Meghna Natraj
1
这是一个不错的解决方案,但最好也将标签更改为百分比。 - Pengju Zhao
你知道如何用百万来表达数字吗?例如,500k表示为0.5m。 - user147529

28

将 ".1f" 替换为 ".1%",这样应该就解决了您的问题。

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

2
然后,颜色映射将从0到1而不是0到100。 - ilija139
谢谢!这正是我在谷歌上寻找的! - Fernando Wittmann
@ilija139 你说得对。请看我的回答,解决了colorbar的问题。 - Gobryas
@ilija139 你说得对。请看我的回答,解决了颜色条的问题。 - undefined

1

您需要同时使用fmt参数调整“注释”的格式和cbar_kws调整“colorbar”的格式。

from matplotlib.ticker import FuncFormatter
fmt = lambda x,pos:'{:.0%}'.format(x)
hm = sns.heatmap(data=S, annot=True, ax=ax1, fmt='.1%', cbar_kws={'format': FuncFormatter(fmt)})

请参考此seaborn issue


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接