Python:查找等高线matplotlib.pyplot.contour()

发布于 2021-01-29 19:18:56

我在找(但不是画画!)某些数据的等高线:

from pprint import pprint 
import matplotlib.pyplot 
z = [[0.350087, 0.0590954, 0.002165], [0.144522, 0.885409, 0.378515], 
     [0.027956, 0.777996, 0.602663], [0.138367, 0.182499, 0.460879], 
     [0.357434, 0.297271, 0.587715]] 
cn = matplotlib.pyplot.contour(z)

我知道’cn’包含了我想要的轮廓线,但我似乎无法到达

他们。我试过几种方法:

print dir(cn) 
pprint(cn.collections[0]) 
print dir(cn.collections[0]) 
pprint(cn.collections[0].figure) 
print dir(cn.collections[0].figure)

无济于事。我知道“cn”是一个“轮廓集”,而且中国大陆收藏是一个数组

我认为“LineCollection”是一个line数组

片段,但我不知道如何提取这些片段。

我的最终目标是创建一个在世界地图上绘制数据的KML文件,并且

这些数据的等高线。

然而,由于我的一些数据点离得很近,而另一些则很远

现在,我需要组成轮廓的实际多边形(线串),而不是

只是轮廓的光栅图像。

我有点惊讶“qhull”不会这样做。

使用Mathematica的“listcurtourplot”,然后将其导出为SVG可以工作,但是我

想用开源的东西。

我不能使用众所周知的CONREC算法,因为我的数据不在网格上

(对于给定的x值,并不总是有多个y值,反之亦然)。

解决方案不必使用python,但必须是开源的,并且

可在Linux上运行。

关注者
0
被浏览
231
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    通过在集合和路径上循环并使用
    的“iter_segments()”方法
    matplotlib.path.Path.

    下面是一个函数,它将顶点作为
    等高线、等高线截面和x、y顶点阵列:

    import numpy as np
    
    def get_contour_verts(cn):
        contours = []
        # for each contour line
        for cc in cn.collections:
            paths = []
            # for each separate section of the contour line
            for pp in cc.get_paths():
                xy = []
                # for each segment of that section
                for vv in pp.iter_segments():
                    xy.append(vv[0])
                paths.append(np.vstack(xy))
            contours.append(paths)
    
        return contours
    

    Edit:

    也可以在不绘制任何东西的情况下使用
    未记录的matplotlib.\u cntrC模块:

    from matplotlib import pyplot as plt
    from matplotlib import _cntr as cntr
    
    z = np.array([[0.350087, 0.0590954, 0.002165],
                  [0.144522,  0.885409, 0.378515],
                  [0.027956,  0.777996, 0.602663],
                  [0.138367,  0.182499, 0.460879], 
                  [0.357434,  0.297271, 0.587715]])
    
    x, y = np.mgrid[:z.shape[0], :z.shape[1]]
    c = cntr.Cntr(x, y, z)
    
    # trace a contour at z == 0.5
    res = c.trace(0.5)
    
    # result is a list of arrays of vertices and path codes
    # (see docs for matplotlib.path.Path)
    nseg = len(res) // 2
    segments, codes = res[:nseg], res[nseg:]
    
    fig, ax = plt.subplots(1, 1)
    img = ax.imshow(z.T, origin='lower')
    plt.colorbar(img)
    ax.hold(True)
    p = plt.Polygon(segments[0], fill=False, color='w')
    ax.add_artist(p)
    plt.show()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看