Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

python - 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 = np.array([[0,2],[3,4]],dtype=int)
plt.imshow(resr)

enter image description here

This looks right. When I try and pass a cmap of my specified colors using:

cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1) 
plt.imshow(resr, cmap=cmap)

I see:

enter image description here

For some reason, the color cmap1[3] is being mapped to the resr values 3 and 4. Why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...