问题
When I plot the pcolormesh plot use the colormap from matplotlib.cm
(like "jet"
, "Set2"
, etc), I can use:
cMap = plt.cm.get_cmap("jet",lut=6)
The colorbar shows like this:
But if I want to call the colormap from the Basemap
package (like GMT_drywet
, GMT_no_green
, etc). I can't use plt.cm,get_cmap
to get these colormap and divide them.
Does mpl_toolkits.basemap.cm
have a similiar function like lut
?
回答1:
As long as the plot you are making has discrete color values (e.g. contour
or contourf
), then colorbar
should automatically generate a colorbar with discrete steps. Here's a plot based on the first example from the basemap documentation:
from mpl_toolkits.basemap import Basemap, cm
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 1)
ax.hold(True)
map = Basemap(projection='ortho',lat_0=45,lon_0=-100,resolution='l')
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral',lake_color='aqua')
map.drawmapboundary(fill_color='aqua')
map.drawmeridians(np.arange(0,360,30))
map.drawparallels(np.arange(-90,90,30))
nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1)
lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:])
lons = (delta*np.indices((nlats,nlons))[1,:,:])
wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons))
mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.)
x, y = map(lons*180./np.pi, lats*180./np.pi)
map.contourf(x,y,wave+mean,15, alpha=0.5, cmap=cm.GMT_drywet)
cb = map.colorbar()
plt.show()
回答2:
Expanding on @tacaswell's comment above, you can achieve the same functionality using the _resample
method. This will produce segmented colormaps for pcolor
/pcolormesh
plots which don't generate discrete-stepped colorbars like contourf
. To achieve the same effect as you did with jet in your question:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import cm
plt.figure()
cmap = cm.GMT_drywet._resample(6)
pm = plt.pcolormesh(np.random.rand(10,8), cmap=cmap)
plt.colorbar(pm, orientation='horizontal')
plt.show()
来源:https://stackoverflow.com/questions/34574934/how-can-i-create-a-discrete-colorbar-using-a-colormap-from-mpl-toolkits-basemap