简体   繁体   中英

Get each level of a contour - Matplotlib

I'm wondering how, given contour lines generate trough the contour() function from Matplotlib, one can iterate to each level to get its vertices. I know that I can iterate over the paths with this code:

cs = plt.contour(x, y, (f - g))
for collection in cs.collections:
    paths = collection.get_paths()
    for path in paths:
        print(path.vertices.shape)

plt.show()

However, how could I find the level of each path, or directly iterate over each level of a contour?

Thank you.

This is maybe very clear to you, but I would like to highlight that care is needed with the proposed code.

See also: https://github.com/matplotlib/matplotlib/issues/367

Each path may be just an array of vertices corresponding to a single open or closed polygon, which is what most people expect, but a path may also correspond to 2 or more polygons if the member codes is set to indicate at which indices the polygons start. Naive use of the paths may not be what is wanted; often the use of path.to_polygons() is better.

In short, this code will work as expected on most simple examples but might cause problems for complex cases. A better alternative is:

cs = plt.contour(x, y, (f - g))
for collection in cs.collections:
    for path in collection.get_paths():
        print path.to_polygons()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM