Skip to content Skip to sidebar Skip to footer

Matplotlib: Listedcolormap Not Mapping Colors

I am having trouble understanding why a custom cmap is not being properly mapped to an image using plt.imshow. When I plot the 2-D array resr without specifying a cmap, I see: resr

Solution 1:

I see two options here:

A. Map data to categories

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable

resr = np.array([[0,2],[3,4]],dtype=int)
u, ind = np.unique(resr, return_inverse=True)
norm = colors.BoundaryNorm(np.arange(len(u)+1)-.5, len(u))
cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1) 

fig,ax = plt.subplots()
im = ax.imshow(ind.reshape(resr.shape), cmap=cmap,norm=norm)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%")

cb = plt.colorbar(im, cmap=cmap,norm=norm,cax=cax)

cb.set_ticks(np.arange(len(u)))
cb.ax.set_yticklabels(cmap1)
cb.ax.tick_params(labelsize=10)

plt.show()

B. Map categories to data

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable

resr = np.array([[0,2],[3,4]],dtype=int)

u = np.unique(resr)
bounds = np.concatenate(([resr.min()-1], u[:-1]+np.diff(u)/2. ,[resr.max()+1]))
print(bounds)
norm = colors.BoundaryNorm(bounds, len(bounds)-1)
cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1) 

fig,ax = plt.subplots()
im = ax.imshow(resr, cmap=cmap,norm=norm)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%")

cb = plt.colorbar(im, cmap=cmap,norm=norm,cax=cax)

cb.set_ticks(bounds[:-1]+np.diff(bounds)/2.)
cb.ax.set_yticklabels(cmap1)
cb.ax.tick_params(labelsize=10)

plt.show()

The result is the same for both cases.

enter image description here

Solution 2:

Following @ImportanceOfBeingErnest's comment providing a link to their post, I was able to find a solution.

The trick was to use pass np.unique(resr) to BoundaryNorm. Something like:

resr = np.array([[0,2],[3,4]],dtype=int)

norm = colors.BoundaryNorm(np.unique(resr), len(np.unique(resr))-1)
cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1) 
plt.imshow(resr, cmap=cmap,norm=norm);plt.colorbar()

Which returns the expected result:

enter image description here

Post a Comment for "Matplotlib: Listedcolormap Not Mapping Colors"