matplotlib介绍如何从等高线中提取数据



我想从不同等值线的轮廓中获取数据。matplotlib问题-从等高线提取数据给出了一个示例

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()
coord = cs.collections[0].get_paths()

得到了euqal值为9.5的直线坐标。

现在,我需要从一个轮廓中获得多等值线的坐标,所以我需要改变值来表示不同的线,但当我使用循环时,这意味着python需要在每个循环中构造轮廓,我如何构造一次轮廓,然后改变值来代表不同的线?

您可以使用plt.contour一次绘制多个轮廓,方法是列出要绘制轮廓的值。然后,您可以使用cs.allsegs或对cs.collections列表中的每个项目使用get_paths从返回的ContourSet中访问它们。

例如:

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, 10.5, 11.5])
plt.show()
# Option 1: use allsegs
all_coords = cs.allsegs
print(all_coords)
# Option 2: use cs.collections[X].get_paths()
coords1 = cs.collections[0].get_paths()
coords2 = cs.collections[1].get_paths()
coords3 = cs.collections[2].get_paths()
print(coords1)
print(coords2)
print(coords3)

打印的坐标在哪里:

选项1(allsegs(:

[[array([[4.        , 1.625     ],
[3.25      , 2.        ],
[3.        , 2.16666667],
[2.16666667, 3.        ],
[2.        , 3.25      ],
[1.625     , 4.        ]])],
[array([[4.        , 1.375     ],
[3.        , 1.83333333],
[2.75      , 2.        ],
[2.        , 2.75      ],
[1.83333333, 3.        ],
[1.375     , 4.        ]])],
[array([[4.   , 1.125],
[3.   , 1.5  ],
[2.25 , 2.   ],
[2.   , 2.25 ],
[1.5  , 3.   ],
[1.125, 4.   ]])]]

选项2(get_paths()(:


[Path(array([[4.        , 1.625     ],
[3.25      , 2.        ],
[3.        , 2.16666667],
[2.16666667, 3.        ],
[2.        , 3.25      ],
[1.625     , 4.        ]]), array([1, 2, 2, 2, 2, 2], dtype=uint8))]
[Path(array([[4.        , 1.375     ],
[3.        , 1.83333333],
[2.75      , 2.        ],
[2.        , 2.75      ],
[1.83333333, 3.        ],
[1.375     , 4.        ]]), array([1, 2, 2, 2, 2, 2], dtype=uint8))]
[Path(array([[4.   , 1.125],
[3.   , 1.5  ],
[2.25 , 2.   ],
[2.   , 2.25 ],
[1.5  , 3.   ],
[1.125, 4.   ]]), array([1, 2, 2, 2, 2, 2], dtype=uint8))]   

最新更新