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

Matplotlib等高线数值与计算值不符问题咨询

等高线图绘制异常问题排查

问题现象

  • 点(1,1)的计算值为√(1²+1²)≈1.41,却出现在标注1.5和2.0的等高线之间,逻辑上应处于1.0和1.5之间;
  • 点(0.707,0.707)的计算值为√(0.707²+0.707²)=1,却落在1.5等高线上,本该位于1.0等高线上。

测试代码

import numpy as np
import matplotlib.pyplot as plt

zval = 1
xval = np.sqrt(zval**2/2)
print(xval)   # 0.707
yval = xval
print(yval)
print(np.sqrt(xval**2 + yval**2))  # 1

xlist = np.linspace(-3.0, 3.0, 3)
ylist = np.linspace(-3.0, 3.0, 4)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)

fig = plt.figure(figsize=(7,6))
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax = fig.add_axes([left, bottom, width, height]) 

cp = ax.contour(X, Y, Z)
ax.clabel(cp, inline=True, 
          fontsize=10)
ax.set_title('Contour Plot')
ax.set_xlabel('x (cm)')
ax.set_ylabel('y (cm)')

# Z value is 1 but point is plotted beyond the 1.5 line -- why?
ax.scatter(
    x=xval, 
    y=yval,
    color="orange"
)

ax.scatter(1,1, color="red")
print(np.sqrt(1**2 + 1**2))

plt.grid()
plt.show()

问题原因

网格采样点过于稀疏:

  • xlist仅生成3个点:-3、0、3
  • ylist仅生成4个点:-3、-1、1、3

等高线绘制依赖网格点的Z值进行插值计算,如此稀疏的网格无法准确还原√(x²+y²)的圆形等高线,matplotlib只能基于有限的点做粗糙插值,最终导致等高线严重变形,出现点与等高线位置不匹配的异常。

解决方案

大幅增加网格的采样点数,比如将xlist和ylist的采样数量改为50个:

xlist = np.linspace(-3.0, 3.0, 50)
ylist = np.linspace(-3.0, 3.0, 50)

密集的网格能提供足够的Z值信息,matplotlib可以准确计算出符合预期的圆形等高线,两个测试点也会落在对应的等高线位置上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 19:19:56