pceccon
pceccon

Reputation: 9844

Get levels (contour) of a scalar field (Matplotlib / Python)

I'm wondering how can I get the vertices of each level of a contour plot.

For example, I have this plot:

enter image description here

Which has, I guess, more than 10 levels.

I'm trying to get the vertices of each one of them.

So far, I have this piece of code:

def iso_contours(scalar_fields):
    for scalar_field in scalar_fields:
        cs = plt.contour(scalar_field)
        paths = cs.collections[0].get_paths()
        print len(path)
        for path in paths:
            # Get vertices

However, I'm getting just one path. How is the properly way to achieve what I would like to?

Thank you in advance.

Upvotes: 0

Views: 1233

Answers (1)

unutbu
unutbu

Reputation: 879849

Use path.vertices:

import matplotlib.pyplot as plt
import numpy as np

x, y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))
f = x ** y
g = y ** x
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()

yields

(7, 2)
(28, 2)
(51, 2)
(172, 2)
(154, 2)
(51, 2)
(28, 2)
(7, 2)

enter image description here

Upvotes: 1

Related Questions