假设边界是作为多边形顶点的列表给出的,您可以让 matplotlib 在数据坐标上为您生成一个掩码,然后使用该掩码仅对轮廓内的值求和。
换句话说,当您有一系列坐标来定义标记感兴趣区域的多边形边界时,让 matplotlib 生成一个布尔掩码,指示该多边形内的所有坐标。然后可以使用此掩码仅提取轮廓内有限的降雨数据集。
以下简单示例向您展示了这是如何完成的:
import numpy as np
from matplotlib.patches import PathPatch
from matplotlib.path import Path
import matplotlib.pyplot as plt
# generate some fake data
xmin, xmax, ymin, ymax = -10, 30, -4, 20
y,x = np.mgrid[ymin:ymax+1,xmin:xmax+1]
z = (x-(xmin+xmax)/2)**2 + (y-(ymin + ymax)/2)**2
extent = [xmin-.5, xmax+.5, ymin-.5, ymax+.5]
xr, yr = [np.random.random_integers(lo, hi, 3) for lo, hi
in ((xmin, xmax), (ymin, ymax))] # create a contour
coordlist = np.vstack((xr, yr)).T # create an Nx2 array of coordinates
coord_map = np.vstack((x.flatten(), y.flatten())).T # create an Mx2 array listing all the coordinates in field
polypath = Path(coordlist)
mask = polypath.contains_points(coord_map).reshape(x.shape) # have mpl figure out which coords are within the contour
f, ax = plt.subplots(1,1)
ax.imshow(z, extent=extent, interpolation='none', origin='lower', cmap='hot')
ax.imshow(mask, interpolation='none', extent=extent, origin='lower', alpha=.5, cmap='gray')
patch = PathPatch(polypath, facecolor='g', alpha=.5)
ax.add_patch(patch)
plt.show(block=False)
print(z[mask].sum()) # prints out the total accumulated
在此示例中,x
并y
表示您的UTM-X
和UTM-Y
数据范围。z
表示天气降雨量数据,但在这种情况下是一个矩阵,与平均降雨量的单列视图不同(它很容易重新映射到网格上)。
在最后一行,我总结了z
轮廓内的所有值。如果你想要平均值,只需替换sum
为mean
.