如何使用文本标签在 Seaborn 热图中自定义颜色条

How to customize colorbar in Seaborn Heatmap with text labels

我想为热图创建一个颜色条图例,而不是数字,而是文本。

例如,假设我要显示穿梭于某些城市之间的人员分布。但是在 colorbar 中,我想要三个文本 "Low population"、"medium" 和 "High" 而不是显示人口范围的数字。

一点也不专业,但是我解决这个问题的代码在打击中:

ax = sns.heatmap(Matrix_of_Population, cmap='viridis', cbar_kws={'label': 'Low      Medium    high'})

但人口数也不止这些文字

您可以为颜色条中的特定刻度指定标签:

import seaborn as sns
import numpy as np 


a = np.random.randn(20,20)
ax = sns.heatmap(a, cmap='viridis')
c_bar = ax.collections[0].colorbar
c_bar.set_ticks([-2, 0, 2])
c_bar.set_ticklabels(['Low', 'Medium', 'High'])