pythonmatplotlibseaborncolorbar

Center colorbar Labels on Heatmap


I have seen a few similar questions to this but haven't been able to make it work so I figured I would ask here.

I have a seaborn heatmap with 2 overlaid scatter plots. When it plots the colorbar the labels aren't centered on the colors. I was wondering how to center the values on the colors. Also is it possible to always set the 0 color as white? My code and plot is below

fig, ax = plt.subplots(figsize=(20, 20))

plt.gca().set_aspect(RI/SI)
cbar_kws=dict(pad=0.01,shrink=0.86, drawedges=True, ticks=range(int(maxfold)+1)) #Colorbar size and location 

cmap = plt.get_cmap('jet', maxfold+1)

sns.heatmap(binspivot, cmap=cmap,linewidths=0.01, linecolor = 'black', vmin=0, vmax=maxfold, xticklabels=False, yticklabels=False,annot=True, annot_kws={"size": 20,"color":"black"},cbar_kws=cbar_kws)
ax.set(xlabel=None, ylabel=None)
ax.scatter(Sourcedfcut['Xmod'],Sourcedfcut['Ymod'], color="red", s = 400)
ax.scatter(Recdfcut['Xmod'],Recdfcut['Ymod'], color="blue", s= 400)

Results


Solution

  • The easiest way to have the tick marks of the colorbar at the center of the rectangles, is to move vmin and vmax by one half. To add an extra color to an existing colormap, one can create a new ListedColormap using that new color and colors extracted from the original colormap. To make the white in the colorbar visible against a white background, a black surrounding rectangle can be added.

    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    import seaborn as sns
    import numpy as np
    
    binspivot = (12.02 * np.random.rand(20, 20) ** .5).astype(int)
    maxfold = binspivot.max()
    fig, ax = plt.subplots(figsize=(20, 20))
    
    cbar_kws = dict(pad=0.01, shrink=0.86, drawedges=True, ticks=range(int(maxfold) + 1))  # Colorbar size and location
    
    cmap1 = plt.get_cmap('turbo', maxfold + 1)
    colors = ['white'] + list(plt.get_cmap('turbo', maxfold).colors)
    cmap = ListedColormap(colors=colors)
    
    sns.heatmap(binspivot, cmap=cmap, linewidths=0.01, linecolor='black', vmin=-0.5, vmax=maxfold + 0.5,
                xticklabels=False, yticklabels=False,
                annot=True, annot_kws={"size": 20}, cbar_kws=cbar_kws, ax=ax)
    ax.set(xlabel=None, ylabel=None)
    cbar_ax = fig.axes[-1]
    cbar_ax.tick_params(labelsize=20)
    cbar_ax.add_patch(plt.Rectangle((0, 0), 1, 1, fc='none', ec='black', clip_on=False, transform=cbar_ax.transAxes))
    plt.tight_layout()
    plt.show()
    

    sns.heatmap, colorbar tick labels centered