4

This question/answer pair shows how to extract vertices from contour plot:

p = cs.collections[0].get_paths()[0]
v = p.vertices
x = v[:,0]
y = v[:,1]

But how to get the value (i.e z for an elevation model) for each path?

Community
  • 1
  • 1
WKT
  • 263
  • 3
  • 9

1 Answers1

5

There's no direct way, but cs.collections is in the exact same order as cs.levels (which is the "z" values you're after).

Therefore, it's easiest to do something like:

lookup = dict(zip(cs.collections, cs.levels))
z = lookup[line_collection_artist]

As a quick interactive example:

import numpy as np
import matplotlib.pyplot as plt

def main():
    fig, ax = plt.subplots()
    cs = ax.contour(np.random.random((10,10)))

    callback = ContourCallback(cs)
    plt.setp(cs.collections, picker=5)
    fig.canvas.mpl_connect('pick_event', callback)

    plt.show()

class ContourCallback(object):
    def __init__(self, cs):
        self.lookup = dict(zip(cs.collections, cs.levels))

    def __call__(self, event):
        print self.lookup[event.artist]

main()
Joe Kington
  • 275,208
  • 71
  • 604
  • 463