Search code examples
pythonmatplotliblegendheatmapcolorbar

How to customize colorbar in Seaborn Heatmap with text labels


I'd like to create a colorbar legend for a heatmap, that instead of numbers has text.

For example, suppose I am going to show the people distribution who traverse between some cities. But in colorbar, I want to have three texts "Low population", "medium" and "High" instead of number which shows the range of the population.

It is not professional at all but my code to address this issue is in the blow:

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

But the number of population is also besides these texts.


Solution

  • You can specify labels for specific ticks in the colorbar:

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

    enter image description here