Python:从matplotlib.pyplot.contour()查找轮廓线 [英] Python: find contour lines from matplotlib.pyplot.contour()

查看:159
本文介绍了Python:从matplotlib.pyplot.contour()查找轮廓线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找(但不绘制!)轮廓线以获取某些数据:

I'm trying to find (but not draw!) contour lines for some data:

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包含我想要的轮廓线,但我似乎无法 给他们.我已经尝试了几件事:

I know cn contains the contour lines I want, but I can't seem to get to them. I've tried several things:

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

无济于事.我知道cnContourSet,而cn.collections是数组 的LineCollection s.我认为LineCollection是线段的数组,但是我 无法弄清楚如何提取这些细分.

to no avail. I know cn is a ContourSet, and cn.collections is an array of LineCollections. I would think a LineCollection is an array of line segments, but I can't figure out how to extract those segments.

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

My ultimate goal is to create a KML file that plots data on a world map, and the contours for that data as well.

但是,由于我的一些数据点相互靠近,而另一些 在很远的地方,我需要组成的实际多边形(线串) 轮廓,而不仅仅是轮廓的栅格化图像.

However, since some of my data points are close together, and others are far away, I need the actual polygons (linestrings) that make up the contours, not just a rasterized image of the contours.

我有些惊讶,qhull没有做这样的事情.

I'm somewhat surprised qhull doesn't do something like this.

使用Mathematica的ListContourPlot,然后以SVG格式导出,但是我 想要使用开源的东西.

Using Mathematica's ListContourPlot and then exporting as SVG works, but I want to use something open source.

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

I can't use the well-known CONREC algorithm because my data isn't on a mesh (there aren't always multiple y values for a given x value, and vice versa).

解决方案不必使用python,但必须是开源的 并且可以在Linux上运行.

The solution doesn't have to python, but does have to be open source and runnable on Linux.

推荐答案

通过遍历集合和路径并使用

You can get the vertices back by looping over collections and paths and using the iter_segments() method of matplotlib.path.Path.

这是一个函数,将顶点作为一组嵌套的轮廓线,轮廓线和x,y顶点数组的嵌套列表返回:

Here's a function that returns the vertices as a set of nested lists of contour lines, contour sections and arrays of x,y vertices:

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模块,也可以在不绘制任何内容的情况下计算轮廓:


It's also possible to compute the contours without plotting anything using the undocumented matplotlib._cntr C module:

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

这篇关于Python:从matplotlib.pyplot.contour()查找轮廓线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆