Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Colormap

I want to plot a heatmap with a custom colormap similar to this one, although not exactly.

enter image description here

I'd like to have a colormap that goes like this. In the interval [-0.6, 0.6] the color is light grey. Above 0.6, the color red intensifies. Below -0.6 another color, say blue, intensifies.

How can I create such a colormap using python and matplotlib?

What I have so far: In seaborn there is the command seaborn.diverging_palette(220, 10, as_cmap=True) which produces a colormap going from blue-light grey-red. But there is still no gap from [-0.6, 0.6].

enter image description here

like image 423
r0f1 Avatar asked Oct 03 '18 11:10

r0f1


1 Answers

Colormaps are normalized in the 0..1 range. So if your data limits are -1..1, -0.6 would be normalized to 0.2, +0.6 would be normalized to 0.8.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors

norm = matplotlib.colors.Normalize(-1,1)
colors = [[norm(-1.0), "darkblue"],
          [norm(-0.6), "lightgrey"],
          [norm( 0.6), "lightgrey"],
          [norm( 1.0), "red"]]

cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", colors)


fig, ax=plt.subplots()
x = np.arange(10)
y = np.linspace(-1,1,10)
sc = ax.scatter(x,y, c=y, norm=norm, cmap=cmap)
fig.colorbar(sc, orientation="horizontal")
plt.show()

enter image description here

like image 97
ImportanceOfBeingErnest Avatar answered Sep 27 '22 22:09

ImportanceOfBeingErnest