Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sure 0 gets white in a RdBu colorbar

I create a heatmap with the following snippet:

import numpy as np
import matplotlib.pyplot as plt
d = np.random.normal(.4,2,(10,10))
plt.imshow(d,cmap=plt.cm.RdBu)
plt.colorbar()
plt.show()

The result is plot below: enter image description here

Now, since the middle point of the data is not 0, the cells in which the colormap has value 0 are not white, but rather a little reddish.

How do I force the colormap so that max=blue, min=red and 0=white?

like image 809
LudvigH Avatar asked Jul 24 '19 10:07

LudvigH


1 Answers

Use a DivergingNorm.

Note: From matplotlib 3.2 onwards DivergingNorm is renamed to TwoSlopeNorm

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

d = np.random.normal(.4,2,(10,10))

norm = mcolors.DivergingNorm(vmin=d.min(), vmax = d.max(), vcenter=0)
plt.imshow(d, cmap=plt.cm.RdBu, norm=norm)

plt.colorbar()
plt.show()

enter image description here

like image 80
ImportanceOfBeingErnest Avatar answered Oct 23 '22 19:10

ImportanceOfBeingErnest