numpy—用于在griddata绘图中提取数据的python函数

to94eoyn  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(342)

我有以下代码和绘图:

import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
def func(x, y):
    return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
grid_x, grid_y = np.mgrid[0:1:200j, 0:1:200j]
rng = np.random.default_rng()
points = rng.random((1000, 2))
values = func(points[:,0], points[:,1])
grid_z = griddata(points, values, (grid_x, grid_y), method='linear')
plt.xlabel("Degrees")
plt.ylabel("Degrees")
plt.imshow(grid_z, extent=(-0.5,0.5,-0.5,0.5), origin='lower')

我想提取圆心半径为0.25°的圆形区域内所有点的平均值,在上述图中居中。并提取内径为0.1º、外径为0.2º的环形内所有值的平均值。
谢谢你的帮助

hjzp0vay

hjzp0vay1#

你需要做的第一件事就是给你的圆加上一个布尔掩码。然后你可以把它应用到 grid_z 隔离圆内的所有值并计算其平均值。
更好的方法是直接在屏幕上使用遮罩 grid_xgrid_y 仅在所需点上插值函数。


# Compute the mask of a circle

center_grid_x = 0.5
center_grid_y = 0.5
radius = 0.25
mask = (grid_x - center_grid_x)**2 + (grid_y - center_grid_y)**2 < radius**2

# The mask can be visualized with

# plt.imshow(mask)

# Apply the mask to grid_z and compute the mean

mean1 = np.mean(grid_z[mask])

# Or better compute only the values of points inside the circle

values_z = griddata(points, values, (grid_x[mask], grid_y[mask), method='linear')
mean2 = np.mean(values_z)

相关问题