how to get the level of a path in matplotlib contour

Viewed 33

I'm working on contourf to get the contours of some gridded data. But I do not understand how to get the correspondent level of every path (neither do I know for polygons) returned by contourf.

Needless to say this information is present, since when plotted different levels correspond to different colours.

Trivial code example:

import numpy
from matplotlib import pyplot

grid = numpy.empty((5,5))

grid[:2] = 0
grid[2:] = 2

print(grid)

contour_set = pyplot.contourf(range(5), range(5), grid, levels=[1,2]) 
#at least two levels are needed so i give a random one

polygon = contour_set.collections[0].get_paths()[0].to_polygons()[0]

print(polygon)

Here the path is clearly of level '2' but the issue comes when there are many different levels.

1 Answers

IIUC the contour_set.levels array contains the information you are after. Disregard the first element, since that doesn't correspond to any polygon (level 1 in your case):

for level, collection in zip(contour_set.levels[1:], contour_set.collections):
    print(f"%% Level {level} %%")
    print(collection.get_paths()[0].to_polygons())

"... correspondent level of every path ... " => Note that the levels correspond to a collection, not to a path (think two peaks, where a given collection might include two circles (paths), corresponding to the same level)

Related