You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib中find_nearest_contour已弃用,如何实现等效功能?

替代Matplotlib 3.8中弃用的find_nearest_contour获取最近等高线段范围的方法

Matplotlib 3.8弃用了ContourSet.find_nearest_contour方法,以下是实现等效功能的代码,可准确定位到距离目标点(x0, y0)最近的等高线段并计算其x、y范围:

import numpy as np
import matplotlib.pyplot as plt

# 假设已有x, y, image数据,以及目标点x0, y0和目标层级level
fig, ax = plt.subplots()
cs = ax.contour(x, y, image, [level])

# 目标层级的所有线段(因为仅指定单个level,所以取cs.allsegs[0])
all_segments = cs.allsegs[0]

min_dist_sq = np.inf
nearest_segment = None

for seg in all_segments:
    # 计算线段上每个点到(x0,y0)的距离平方
    dist_sq = (seg[:, 0] - x0)**2 + (seg[:, 1] - y0)**2
    current_min_dist_sq = dist_sq.min()
    # 更新最近线段
    if current_min_dist_sq < min_dist_sq:
        min_dist_sq = current_min_dist_sq
        nearest_segment = seg

# 计算最近线段的x、y范围
if nearest_segment is not None:
    min_x = nearest_segment[:, 0].min()
    max_x = nearest_segment[:, 0].max()
    min_y = nearest_segment[:, 1].min()
    max_y = nearest_segment[:, 1].max()

逻辑说明

  • 从ContourSet.allsegs中提取目标层级的所有离散线段,当仅传入单个level时,cs.allsegs[0]对应该层级的全部线段
  • 遍历每个线段,计算线段上所有点到目标点的距离平方最小值,以此作为该线段到目标点的最近距离
  • 筛选出距离最小的线段后,直接计算其x、y极值,和原代码功能完全匹配
  • 全程使用Matplotlib公开接口实现,不依赖私有API,彻底规避弃用警告

内容的提问来源于stack exchange,提问作者matteo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 19:02:40