Search code examples
pythonmatplotlibseaborn

How can I plot just the colorbar of a heatmap?


I would like to plot just the colorbar for a heatmap. Here is a MWE:

import seaborn as sns
import io
import matplotlib.pyplot as plt
import numpy as np


A = np.random.rand(100,100)

g = sns.heatmap(A)
plt.show()

How can I plot just its colorbar and not the heatmap itself?


Solution

  • Try to handle it manually:

    import matplotlib as mpl
    import numpy as np
    
    fig, ax = plt.subplots(figsize=(1, 4))
    # vmin, vmax =  np.nanmin(A), np.nanmax(A)
    cmap = mpl.colormaps['rocket']
    norm = mpl.colors.Normalize(0, 1)  # or vmin, vmax
    cbar = fig.colorbar(mpl.cm.ScalarMappable(norm, cmap), ax)
    plt.tight_layout()
    plt.show()
    

    Output:

    enter image description here