Search code examples
pythonmatplotlibseabornheatmapcolorbar

Moving label of seaborn color bar


I've got a seaborn heat map with a labelled color bar using:

seaborn.heatmap(df, cbar_kws = {'label': 'Label for color bar axis'})

but the colorbar's label overlaps with its tick labels. Is there a way to reposition this label further from the ticks (in my case, further to the right) like the 'padding' options for a normal matplotlib plot?


Solution

  • Unfortunately cbar_kws doesn't accept the labelpad argument. Therefore one way to add some padding to the labels will be to access the colorbar after it has been drawn.

    You can use ax.collections[0].colorbar to get access to the matplotlib.colorbar.Colorbar object. This then lets you use the colobar as you normally would with matplotlib. So, you can use set_label() to set your colorbars label, and you can use the labelpad= argument:

    import seaborn as sns
    
    uniform_data = np.random.rand(10, 12) # random data
    ax = sns.heatmap(uniform_data)
    
    cbar = ax.collections[0].colorbar
    cbar.set_label('Label for colour bar axis', labelpad=40)
    
    plt.show()
    

    enter image description here