问题
I would like to mask the Land area from Sea Surface Temperature Data over the globe. I am using Cartopy to plot the data.
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from netCDF4 import Dataset
f = Dataset('sst.mnmean.nc')
sst = f.variables['sst'][0,:,:]
lats = f.variables['lat'][:]
lons = f.variables['lon'][:]
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
plot = ax.contourf(lons, lats, sst, 60, transform=ccrs.PlateCarree())
cb = plt.colorbar(plot)
plt.show()
The above code plots data like this:
I would like to mask out the Land from this.
回答1:
I went through the cartopy documentation and came across the method called add_feature. The code is as follows:
import numpy as np
import matplotlib.pyplot as plt
import cartopy as cart
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset
f = Dataset('sst.mnmean.nc')
sst = f.variables['sst'][0,:,:]
lats = f.variables['lat'][:]
lons = f.variables['lon'][:]
ax = plt.axes(projection=cart.crs.PlateCarree())
ax.coastlines()
ax.add_feature(cart.feature.LAND, zorder=100, edgecolor='k')
ax.set_global()
plot = ax.contourf(lons, lats, sst, 60, transform=cart.crs.PlateCarree())
cb = plt.colorbar(plot)
plt.show()
The plot now looks like this.
To mask the oceans, change cart.feature.LAND
to cart.feature.OCEAN
回答2:
For masking land area, it would be easier to use basemap.
from mpl_toolkits.basemap import Basemap
map = Basemap(projection='mill',lon_0=180) # create projection
.... # whatever processing needed
map.fillcontinents(color='coral') # mask land mass
See basemap example here
来源:https://stackoverflow.com/questions/36525825/mask-ocean-or-land-from-data-using-cartopy