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

标签 python numpy matplotlib spatial contour

我正在尝试查找(但不绘制!)某些数据的等高线:

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 是一个 ContourSet,而 cn.collections 是一个数组 LineCollections。我认为 LineCollection 是一个线段数组,但我 无法弄清楚如何提取这些片段。

我的最终目标是创建一个在世界上绘制数据的 KML 文件 map ,以及该数据的轮廓。

但是,由于我的一些数据点靠得很近,而其他数据点 很远,我需要构成的实际多边形(线串) 轮廓,而不仅仅是轮廓的光栅化图像。

我有点惊讶 qhull 没有做这样的事情。

使用 Mathematica 的 ListContourPlot 然后导出为 SVG 工作,但我 想使用一些开源的东西。

我无法使用众所周知的 CONREC 算法,因为我的数据不在 网格(给定的 x 值并不总是有多个 y 值,并且 反之亦然)。

解决方案不必是 python,但必须是开源的 并可在 Linux 上运行。

最佳答案

您可以通过循环遍历集合和路径并使用 matplotlib.path.Pathiter_segments() 方法来取回顶点.

这是一个函数,它以一组嵌套的轮廓线列表、轮廓部分和 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

编辑:

也可以使用未记录的 matplotlib._cntr C 模块计算轮廓而不绘制任何内容:

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

enter image description here

关于Python:从 matplotlib.pyplot.contour() 中查找等高线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18304722/

相关文章:

python - GPU内存溢出: Hyperparameter Tuning loop with varying models

python - 模型不学习

python - matplotlib 中带有欧元符号的刻度

python-3.x - 如何在 PySide QFrame 中自动调整 Matplotlib 图?

python - 将 matplotlib 颜色图转换为 seaborn 调色板

python - 如何使用 Pyramid 缓存?

python - unicode 字符串格式神秘 KeyError。怎么了?

python - 通过 bool 索引数组进行 Numpy 数组赋值

python - 如何从 Python 中的 .txt 文件加载特定行?

python - 累积条件计数