Maecky
Maecky

Reputation: 2038

Set one value to a specific color using matplotlibs colorbar

I have the following code:

matplotlib.pyplot.figure()
matplotlib.pyplot.imshow( myValues )
matplotlib.pyplot.colorbar()
matplotlib.pyplot.title( 'Values' )
matplotlib.pyplot.show()

which creates a pretty default colormap. myValues is in the range from [ -1.0, 1.0 ] (which perhaps changes later. I want to color all values that are 0.0 in white. How can I achieve this?

Regards, Maecky

Upvotes: 0

Views: 4936

Answers (1)

snake_charmer
snake_charmer

Reputation: 3013

This should do the job:

from matplotlib import pyplot as plt
import numpy as np

plt.figure()
myValues = np.random.random((10,10))*2 -1
plt.imshow( myValues ,cmap = "RdBu_r" , vmin=-1, vmax=1)
plt.colorbar()
plt.title( 'Values' )
plt.show()

Where the idea is to :

1- Choose a colormap that is white "in the middle", for instance RdBu_r. For more see:

http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps

2- Fix min and max value at equal distances from zero. In your case vmin=-1, vmax=1 is a obvious choice.

The problem of this solution is that in case you dataset's range is to be changed, values outside [vmin,vmax] will all be mapped to the same color. This may or may not be an issue depending of what you want to do.

Upvotes: 1

Related Questions