I am trying to figure out a way to get the area inside a specific contour line?
I use matplotlib.pyplot to create my contours.
Does anyone have experi
Obviously, the results for r=1,2,3 in @spfrnd's answer are far off the exact areas for circles according to A(r) = pi r^2, even for a rather dense grid. The reason the above code doesn't work properly is that the returned vertices are incomplete due to the clabels generated by
plt.clabel(cs, inline=1, fontsize=10)
and consequently, the shoelace algorithm calculates the wrong area.
You can verify this easily by plotting the returned vertices next to the contour plot (best use a larger delta or keep only every Nth point via the :: operator)
N = 10
vs = cs.collections[0].get_paths()[0].vertices
plt.plot(vs[::N, 0], vs[::N, 1], marker="x", alpha=0.5)
For a visualization, see this picture.
Removing the clabels leads to quite accurate results, even for rather coarse grids. Setting inline=False in the clabel command does the job as well.