I have data for visualization on a map of the USA. I do not want any color on lands outside the United States (in Mexico in the southwest and in Canada in the northeast). How can I hide these areas from the outline? Please note that it doesn’t matter if these state borders are drawn or not.
The code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap, cm, maskoceans
from scipy.interpolate import griddata
np.random.seed(77)
lllat = 24.396308
lllon = -124.848974
urlat = 49.384358
urlon = -66.885444
m = Basemap(llcrnrlat=lllat,
urcrnrlat=urlat,
llcrnrlon=lllon,
urcrnrlon=urlon,
resolution='i', projection='cyl')
m.drawcountries(linewidth=1.0)
m.drawstates(linewidth=1.0, color='lightgray')
m.drawlsmask(land_color='gray',ocean_color="#b0c4de", lakes=True)
lats = np.random.randint(low=lllat-1, high=urlat+1, size=1000) + np.random.ranf(size=1000)
lons = np.random.randint(low=lllon-1, high=urlon+1, size=1000) + np.random.ranf(size=1000)
probabilities = np.random.random(size=1000)
mlon, mlat = m(*(lons, lats))
numcols, numrows = 1000, 1000
xi = np.linspace(mlon.min(), mlon.max(), numcols)
yi = np.linspace(mlat.min(), mlat.max(), numrows)
xi, yi = np.meshgrid(xi, yi)
x, y, z = mlon, mlat, probabilities
zi = griddata((mlon, mlat), probabilities, (xi, yi), method='nearest', rescale=False)
data = maskoceans(xi, yi, zi)
con = m.contourf(xi, yi, data, cmap=plt.get_cmap('YlOrRd'))
cbar = m.colorbar(con,location='right',pad="3%")
plt.show()
which creates the following image
Pay attention to colors outside the borders of the USA. I want them to be deleted.
I tried to remove points from lats and logs that do not exist in the US, but still the outline colors of some parts outside the border.
I could mask the waters with an ocean mask, but I could not mask these points in Mexico and Canada.
. zi nan , , , , .