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

如何在Matplotlib色条图上绘制0值等值线?

解决方案

直接用plt.contour画0值等值线,无需额外生成X/Y坐标

plt.contour可以直接接收你的distance二维数组作为Z值,默认会用数组的行列索引作为X/Y坐标,和plt.imshow的默认坐标体系匹配(注意统一origin参数即可)。

示例代码:

import matplotlib.pyplot as plt

# 显示原图像
plt.imshow(distance)
# 绘制0值等值线,指定levels=[0],设置颜色和线宽
plt.contour(distance, levels=[0], colors='red', linewidths=2, origin='upper')
# 直接保存图像,无需先加色条再移除
plt.savefig(generate_filename("test_images_with_contour.png"))
plt.close()

关键注意点

  • imshow默认origin='upper'(图像左上角为坐标原点),而contour默认origin='lower'(左下角为原点),必须给contour加上origin='upper'参数,才能让等值线和图像位置完全对应。
  • 如果distance对应实际物理坐标,需要自定义X/Y的话,可用np.meshgrid生成坐标网格:
import numpy as np

rows, cols = distance.shape
# 生成X/Y坐标数组
x_coords = np.arange(cols)
y_coords = np.arange(rows)
X, Y = np.meshgrid(x_coords, y_coords)

# 用自定义坐标绘制等值线
plt.imshow(distance, origin='upper')
plt.contour(X, Y, distance, levels=[0], colors='red', linewidths=2)
plt.savefig(generate_filename("test_images_with_contour.png"))

补充:填充等值线区域的替代方法

如果需要给0值两侧区域添加填充效果,可用plt.contourf配合contour使用:

plt.imshow(distance)
# 填充0值以下区域(半透明红色)
plt.contourf(distance, levels=[-np.inf, 0, np.inf], colors=['none', 'rgba(255,0,0,0.2)'], origin='upper')
# 叠加0值等值线
plt.contour(distance, levels=[0], colors='red', linewidths=2, origin='upper')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:40:51