How to add a label to Seaborn Heatmap color bar?

让人想犯罪 __ 提交于 2019-12-21 03:12:06

问题


If I have the following data and 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?


回答1:


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

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'})

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




回答2:


You can use:

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


来源:https://stackoverflow.com/questions/42092218/how-to-add-a-label-to-seaborn-heatmap-color-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!