How to add a label to Seaborn Heatmap color bar?

PythonHeatmapSeaborn

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

enter image description here

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

Solution 2 - Python

You can use:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionishidoView Question on Stackoverflow
Solution 1 - PythonmiraduloView Answer on Stackoverflow
Solution 2 - PythonkezzosView Answer on Stackoverflow