I am using seaborn and have a heatmap. How do I create a colormap with specific colors from a discrete range?

Viewed 300

I am making a seaborn heat map and I want to specify a discrete colormap with these ranges:

under 40 = dark green
40 - 70 = light green
70 - 130 = white
130 - 165 = light red
165 and over = dark red

I made a colorbar with the right boundaries:

fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)

cmap = mpl.colors.ListedColormap(['darkolivegreen', 'yellowgreen', 'white', 'lightcoral','darkred'])
#cmap.set_over('0.25')
#cmap.set_under('0.75')
bounds = [0, 40, 70, 130,165,310]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
cb2 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
                                norm=norm,
                                #boundaries=[0] + bounds + [13],
                                extend='both',
                                ticks=bounds,
                                spacing='proportional',
                                orientation='horizontal')
cb2.set_label('Discrete intervals, some other units')
fig.show()

My issue now is how do I define this colorbar with the boundaries as my new colormap for my seaborn heatmap?

I tried this, but the boundaries are not present and the colormap is adjusted evenly instead of using the specific boundaries.

ax = sns.heatmap(selected,cmap=cmap)
plt.ylabel('Patient')
plt.xlabel('Gene')
#ax.set_yticks(np.arange(0,61,1))
plt.show()

How do I get the correct colormap based off my new colorbar I defined?

1 Answers

You can try using plt.colorbar to plot the color bar after plotting the heatmap

fig, ax = plt.subplots(figsize=(6, 9))
fig.subplots_adjust(bottom=0.5)

# define the color map
cmap = mpl.colors.ListedColormap(['darkolivegreen', 'yellowgreen', 'white', 'lightcoral','darkred'])
bounds = [0, 40, 70, 130,165,310]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# plot heatmap with `imshow`
cb = ax.imshow(selected,cmap=cmap, norm=norm)

# plot colorbar
cb2 = plt.colorbar(cb, #boundaries=[0] + bounds + [13],
                                extend='both',
                                ticks=bounds,
                                spacing='proportional',
                                orientation='horizontal')
cb2.set_label('Discrete intervals, some other units')
fig.show()

Output:

enter image description here

Related