CSV数据插值绘制等高线出现NaN值及Z数组维度问题
问题原因
- 网格范围超出原始散点的凸包:scipy的
griddata函数使用linear/cubic方法时,仅对原始散点构成的凸包内部的点做插值,凸包外的点默认返回NaN。你的原始x轴数据范围是[-3.08, 12.09],y轴范围是[0.02, 10.28],自定义的x范围是[-5,10],部分网格点落在凸包外,因此产生大量NaN。 - 值数组维度错误:你使用
contour_data[[3]].to_numpy()提取z值,得到的是形状为(n,1)的二维数组,插值后输出的Z会是形状为(10,10,1)的三维数组,不符合等高线绘制要求的二维格式。
修正方案
直接修改代码如下:
import numpy as np from scipy.interpolate import griddata import matplotlib.pyplot as plt # 提取x/y坐标点 points = contour_data[[0,1]].to_numpy() # 提取一维z值数组 values = contour_data[3].to_numpy() # 网格范围对齐原始数据的极值,减少凸包外区域 x_min, x_max = points[:,0].min(), points[:,0].max() y_min, y_max = points[:,1].min(), points[:,1].max() # 可适当调高网格分辨率,让等高线更平滑 x = np.linspace(x_min, x_max, 100) y = np.linspace(y_min, y_max, 100) grid_x, grid_y = np.meshgrid(x, y) # 立方插值,可添加fill_value参数指定凸包外的填充值 Z = griddata(points, values, (grid_x, grid_y), method='cubic') # 可选:对剩余NaN用最近邻插值填充,适合需要无缺失值的场景 if np.isnan(Z).any(): from scipy.interpolate import NearestNDInterpolator nan_pos = np.isnan(Z) nearest_interp = NearestNDInterpolator(points, values) Z[nan_pos] = nearest_interp(grid_x[nan_pos], grid_y[nan_pos]) # 绘制等高线 plt.contourf(grid_x, grid_y, Z, cmap='viridis') plt.scatter(points[:,0], points[:,1], c='red', s=5, label='原始散点') plt.legend() plt.colorbar(label='z值') plt.show()
修改后输出的Z为和grid_x/grid_y形状一致的二维数组,可直接用于等高线绘制,NaN问题也得到解决。
内容的提问来源于stack exchange,提问作者Nisa Ulumuddin
相关产品推荐
相关产品推荐

