Question

I am trying to create a custom color map which combines interpolated and discretized color segments. I am hoping that matplotlib's LinearSegmentedColormap can provide such functionality. My test case was to create a 10x10 matrix where row 0 is filled with 0's, row with with 1's, etc. I then attempt to create a color map which interpolates from black to blue, then discretely cuts to red, and then interpolates from red to white. The expected discrete transition from blue to red is not discrete, and instead demonstrates an unexpected interpolation.

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

mat = np.ndarray((10,10))
for i in xrange(10):
    mat[i] = i

colors = ['black', 'blue', 'red', 'white']
index = [0.0, 0.5, 0.5, 1.0]

indx_clr = zip(index, colors)
cm = m.colors.LinearSegmentedColormap.from_list('blue_red', indx_clr, 256)

plt.imshow(mat, cmap=cm)
plt.show()

The unexpected interpolation is shown below, thanks to runnerup.

enter image description here

I have 2 questions.

  1. Why is the blue region interpolated into the red region?
  2. How can I create a color map which combines discrete and interpolated color segments?
Was it helpful?

Solution

This is happening because the default interpolation of imshow is bilinear. Setting it to 'none' will probably make colors appear as you expect.

So add:

plt.imshow(mat, cmap=cm, interpolation='none')

Then it will look like:

enter image description here

If you increase the size of the matrix you will notice that the edge between red and blue is discrete as expected while the rest is interpolated:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top