Page 1 of 1

How to Find the Locations of Any Constant Contour Value

PostPosted: Fri Sep 08, 2017 11:47 am
by yiboj
In some application or research, we may need not only to create the contour plots but also to find out the location of certain contour value. Python package scikit-image is a very useful tool to do all kinds of image processing and manipulation including feature detection, edge finding, filtering and geometrical transformations.

In this recipe, we use skimage.measure.find_contours routine to find constant valued contours in the data array. The skimage routine uses a marching squares method, the array values are linearly interpolated to provide better precision of the output contours. Contours which intersect the image edge are open; all others are closed.

Here is the sample code which uses the MUR L4 dataset file to demonstrate the methodology:

Code: Select all
from matplotlib import pyplot as plt
import numpy as np
from netCDF4 import Dataset
from skimage import measure

# Load MUR L4 netcdf file
filename = ''
ncin = Dataset(filename, 'r')
sst = ncin.variables['analysed_sst'][:]
sst = sst[0,:,:]
lons = ncin.variables['lon'][:]
lats = ncin.variables['lat'][:]

# Create Colormap and Contour Levels
clevs = np.linspace(290, 305, 21)

cs=plt.contourf(lons, lats, sst, clevs, cmap=cmap)

# Find contours at a constant value of 298.0
contours = measure.find_contours(sst, 298.0)

# Draw the location lines
for n, contour in enumerate(contours):
    lons_c = -169.0+contour[:, 1]*0.01
    lats_c = -25.01 + contour[:, 0]*0.01
    if len(lats_c) > 500:
     plt.plot(lons_c, lats_c, color='k', linewidth=2)

# Draw SST colorbar
cb = plt.colorbar(cs)
cb.set_label('SST (K)', fontsize=10)


Here is the output plot. The constant contour locations for SST = 298.0K are shown in black lines.
Figure 1, SST contour plot and the contour location line for SST 298.0 K
contour_loc.png (83.11 KiB) Viewed 15080 times

Re: How to Find the Locations of Any Constant Contour Value

PostPosted: Tue May 28, 2019 5:40 pm
by kevindong
I ran the data recipe and I've been having some difficulties with the plotting part of the contour plot. Image link below: ... sp=sharing