Python 如何为 Seaborn Heatmap 颜色条添加标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42092218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:14:07  来源:igfitidea点击:

How to add a label to Seaborn Heatmap color bar?

pythonheatmapseaborn

提问by ishido

If I have the following data and Seaborn Heatmap:

如果我有以下数据和 Seaborn Heatmap:

import pandas as pd
data = pd.DataFrame({'x':(1,2,3,4),'y':(1,2,3,4),'z':(14,15,23,2)})

sns.heatmap(data.pivot_table(index='y', columns='x', values='z'))

How do I add a label to the colour bar?

如何向颜色条添加标签?

回答by miradulo

You could set it afterwards after collecting it from an ax, or simply pass a label in cbar_kwslike so.

你可以在从 an 收集它之后设置它ax,或者cbar_kws像这样简单地传递一个标签。

import seaborn as sns
import pandas as pd
data = pd.DataFrame({'x':(1,2,3,4),'y':(1,2,3,4),'z':(14,15,23,2)})

sns.heatmap(data.pivot_table(index='y', columns='x', values='z'), 
                             cbar_kws={'label': 'colorbar title'})

enter image description here

在此处输入图片说明

It is worth noting that cbar_kwscan be handy for setting other attributes on the colorbar such as tick frequency or formatting.

值得注意的是,cbar_kws可以方便地在颜色栏上设置其他属性,例如刻度频率或格式。

回答by kezzos

You can use:

您可以使用:

ax = sns.heatmap(data.pivot_table(index='y', columns='x', values='z'))
ax.collections[0].colorbar.set_label("Hello")