Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a discrete colorbar using a colormap from mpl_toolkits.basemap.cm?

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:

enter image description here

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?

like image 534
Han Zhengzu Avatar asked Feb 09 '23 03:02

Han Zhengzu


2 Answers

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()

enter image description here

like image 65
Dan Avatar answered Feb 11 '23 10:02

Dan


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()

enter image description here

like image 20
ali_m Avatar answered Feb 11 '23 10:02

ali_m