How can I calculate the area within a contour in Python using the Matplotlib?

后端 未结 3 855
梦如初夏
梦如初夏 2021-01-01 05:04

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

3条回答
  •  死守一世寂寞
    2021-01-01 06:02

    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.

提交回复
热议问题