Search code examples
matplotlibseaborncolorbar

Seaborn Heatmap Colorbar Custom Location


Given this heatmap:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)

I want to put the colorbar in a custom location (per axis/plot coordinates) with a custom size. Specifically, I want it horizontal in the top left corner (outside of the heatmap) with a small (but not yet defined) size. Is this possible? I know there are general location arguments, but those do not allow for what I want to do. I also know I can define a separate colorbar with plt.colorbar(), but I am not sure how to customize its location either.

Thanks in advance!


Solution

  • You can use "inset axes" to create an ax for the colorbar that goes perfectly together with the subplot. In this tutorial example "cax" is the "ax" for the colorbar. In seaborn's heatmap, cbar_ax is where the colorbar will be placed (when cbar_ax is not given, matplotlib chooses the default position). cbar_kw can set additional keywords for the colorbar, such as setting a horizontal orientation.

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    import numpy as np; np.random.seed(0)
    import seaborn as sns; sns.set_theme()
    
    uniform_data = np.random.rand(10, 12)
    fig, ax = plt.subplots()
    cax = inset_axes(ax,
                     width="40%",  # width: 40% of parent_bbox width
                     height="10%",  # height: 10% of parent_bbox height
                     loc='lower left',
                     bbox_to_anchor=(0, 1.1, 1, 1),
                     bbox_transform=ax.transAxes,
                     borderpad=0,
                     )
    sns.heatmap(uniform_data, ax=ax, cbar_ax=cax, cbar_kws={'orientation': 'horizontal'} )
    plt.subplots_adjust(top=0.8) # make room to fit the colorbar into the figure
    plt.show()
    

    seaborn heatmap with custom placed colorbar