Search code examples
pythoncartopytopography

How to convert Cartopy tiles in gray scale (2022)


I'm trying to display topography data as a background to put some flooding data I have on top. And I want to display this topography in a certain color scale (gray seems to be popular) to avoid having that color in my color bar for the flooding data to avoid confusion.

I'm using Cartopy's img_tiles, and this same problem has actually been asked 4 years ago (How to convert Cartopy tiles in grayscale?). But now the solution (adding cmap="...") doesn't seem to work anymore on the newer version of Cartopy. I have the following error while trying "cmap": error. So, is there a different way to convert the image into a gray scale for plotting?

The code I have is as follow:

import matplotlib.pyplot    as plt
import cartopy.crs          as ccrs
import cartopy.io.img_tiles as cimgt

fig = plt.figure(figsize=(10,7.5))
ax  = plt.axes(projection=ccrs.PlateCarree())

[lon0,lat0,lon1,lat1] = [102., 11., 107., 15.]
ax.set_extent([lon0, lon1, lat0, lat1])

stamen_terrain = cimgt.Stamen(desired_tile_form="L", style="terrain-background") 
ax.add_image(stamen_terrain, 8, cmap='gray')

Without cmap='gray', the code works, but it will give me a fixed color: default color

Edit 1: I have the same problem with ShadeReliefESRI, seems like the problem is not coming from how I acquire the topography data but from how I display it, either with how the axis (ax) was created or how the function ax.add_image() work. The result is the same when I add cmap. Codes are as below:

from cartopy.io.img_tiles import GoogleTiles
class ShadedReliefESRI(GoogleTiles):
    # shaded relief
    def _image_url(self, tile):
        x, y, z = tile
        url = ('https://server.arcgisonline.com/ArcGIS/rest/services/' \
               'World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}.jpg').format(
               z=z, y=y, x=x)
        return url

ax.add_image(ShadedReliefESRI(), 8, cmap ='gray')

Edit 2: Trying to plot with Spyder, funny thing, the figure still show up, looking good, but the error also appears and it prevents me from using savefig().


Solution

  • I have no proplem running your code. I use cartopy version 0.19.0.post1.

    gray-bkg

    If you prefer B/W image for the background, the "toner" maps are available to choose from ref. For example, with this code snippet

    stamen_terrain = cimgt.Stamen(desired_tile_form='RGB', style="toner")
    ax.add_image(stamen_terrain, 8, alpha=0.4)
    

    you can get this plot:

    gray2