4
votes

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:
enter image description here

I would like to mask out the Land from this.

2
Please post your code! - Jason
Please clarify your question, I assume you mean how to remove the temperature data associated with land mass? - Maljam
No, the data is actually just ocean data. But in order to be interpolated effectively, the whole globe is used. As a result I have sea surface temperature over land as well (which is meaningless). Sea surface temperatures is a measure of temperature over just the water bodies - Kushal
@Maljam How did you edit my question to show the image in the question itself? - Kushal
@Kushal there's picture button above the textbox (next to the {} button) - Maljam

2 Answers

13
votes

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
votes

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