【问题标题】:How can I get the (x,y) values of the line that is plotted by a contour plot?如何获得由等高线图绘制的线的 (x,y) 值?
【发布时间】:2010-12-06 08:02:50
【问题描述】:

有没有一种简单的方法来获取这样绘制的等高线的 (x,y) 值:

import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [1,2,3,4]
m = [[15,14,13,12],[14,12,10,8],[13,10,7,4],[12,8,4,0]]
cs = plt.contour(x,y,m, [9.5])
plt.show()

【问题讨论】:

    标签: python matplotlib data-analysis


    【解决方案1】:

    查看返回的 ContourSet 的集合属性。特别是第一个集合的 get_paths() 方法返回组成每条线段的成对点。

    cs.collections[0].get_paths()
    

    要获取坐标的 NumPy 数组,请使用 Path.vertices 属性。

    p1 = cs.collections[0].get_paths()[0]  # grab the 1st path
    coor_p1 = p1.vertices
    

    【讨论】:

    • 这真的很有用,谢谢!您知道在等高线曲线上获取/插值等距点的任何方法吗? (这种方式返回的点不等间距)
    【解决方案2】:

    遍历集合并提取路径和顶点并不是最直接或最快的事情。返回的 Contour 对象实际上通过 cs.allsegs 具有段的属性,它返回形状 [level][element][vertex_coord] 的嵌套列表:

    num_levels = len(cs.allsegs)
    num_element = len(cs.allsegs[0])  # in level 0
    num_vertices = len(cs.allsegs[0][0])  # of element 0, in level 0
    num_coord = len(cs.allsegs[0][0][0])  # of vertex 0, in element 0, in level 0
    

    因此,所有路径的顶点可以提取为:

    cs.allsegs[i][j]  # for element j, in level i
    

    见参考: https://matplotlib.org/3.1.1/api/contour_api.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多