Because matplotlib._cntr
is not supported anymore, you can use the find_contour()
function from skimage
. Here is a simple code to extract a contour level 0.8 from an analytical function from the documentation.
import numpy as np
from skimage import measure
# Construct some test data
x, y = np.ogrid[-np.pi:np.pi:100j, -np.pi:np.pi:100j]
r = np.sin(np.exp((np.sin(x)**3 + np.cos(y)**2)))
# Find contours at a constant value of 0.8
contours = measure.find_contours(r, 0.8)
This will give you the contour in function of (row, column) coordinates along the contour, and not the value of x
and y
. To convert to x
and y
values, you can then interpolate using interp1d
from scipy
:
from scipy.interpolate import interp1d
fx = interp1d(np.arange(0,x.shape[0]), x.flatten())
fy = interp1d(np.arange(0,y.shape[1]), y.flatten())
for contour in contours:
contour[:,0] = fx(contour[:,0])
contour[:,1] = fy(contour[:,1])
Simple code to see the results and validate:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
for contour in contours:
ax.plot(contour[:,0], contour[:,1])
fig.show()
Figure of the extracted contours