matplotlib - extracting values from contour lines

有些话、适合烂在心里 提交于 2021-02-08 03:47:40

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/17051131/matplotlib-extracting-values-from-contour-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!