Erincon
Erincon

Reputation: 399

How to plot dots over contourf in Python using Basemap lib?

I am looking for a simple way to plot dots over certain values in a contourf Basemap plot

Here is an example code:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

dx, dy = 0.5, 0.5

# generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(-15, 15 + dy, dy),
                slice(-90, -60 + dx, dx)]

z = np.sin(x) + np.cos(5 + y*x) * np.cos(x) + x*y/100
n, m = z.shape
z = z - np.exp(np.random.rand(n,m))

#Setup the map
m = Basemap(projection='merc', llcrnrlat=-15, urcrnrlat=15,\
            llcrnrlon=-90, urcrnrlon=-60, resolution='l')
m.drawcoastlines()

xx, yy = m(x,y)
cs = m.contourf(xx,yy,z,cmap=plt.cm.Spectral_r)
cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5)

plt.show()

I'd like that where a = np.where(abs(z) > 5,np.nan,z) Basemap plots dots just like in the figure attached

example

Upvotes: 0

Views: 1891

Answers (1)

Thomas Kühn
Thomas Kühn

Reputation: 9820

You can use hatches in a second call to contourf():

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

dx, dy = 0.5, 0.5

# generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(-15, 15 + dy, dy),
                slice(-90, -60 + dx, dx)]

z = np.sin(x) + np.cos(5 + y*x) * np.cos(x) + x*y/100
n, m = z.shape
z = z - np.exp(np.random.rand(n,m))

#Setup the map
m = Basemap(projection='merc', llcrnrlat=-15, urcrnrlat=15,\
            llcrnrlon=-90, urcrnrlon=-60, resolution='l')
m.drawcoastlines()

xx, yy = m(x,y)
cs = m.contourf(xx,yy,z,cmap=plt.cm.Spectral_r)
cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5)

##adding hatches:
cs = m.contourf(xx, yy, z, levels=[np.min(z),5,np.max(z)], colors='none',
                  hatches=[None,'.',],
                  extend='lower')

plt.show()

gives the following image:

result of the above code

Upvotes: 1

Related Questions