Search code examples
pythonmatplotlibseabornheatmapcolorbar

Move a heatmap colorbar on top of the plot


I have a basic heatmap created using the seaborn library, and want to move the colorbar from the default, vertical and on the right, to a horizontal one above the heatmap. How can I do this?

Here's some sample data and an example of the default:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# Create data
df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])

# Default heatma
ax = sns.heatmap(df)
plt.show()

default heatmap


Solution

  • Looking at the documentation we find an argument cbar_kws. This allows to specify argument passed on to matplotlib's fig.colorbar method.

    cbar_kws : dict of key, value mappings, optional. Keyword arguments for fig.colorbar.

    So we can use any of the possible arguments to fig.colorbar, providing a dictionary to cbar_kws.

    In this case you need location="top" to place the colorbar on top. Because colorbar by default positions the colorbar using a gridspec, which then does not allow for the location to be set, we need to turn that gridspec off (use_gridspec=False).

    sns.heatmap(df, cbar_kws = dict(use_gridspec=False,location="top"))
    

    Complete example:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])
    
    ax = sns.heatmap(df, cbar_kws = dict(use_gridspec=False,location="top"))
    
    plt.show()
    

    enter image description here