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

2024-05-05 00:06:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码和绘图:

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°的圆形区域内所有点的平均值,在上述图中居中

谢谢你的帮助


Tags: 代码import绘图asnppipltrandom
1条回答
网友
1楼 · 发布于 2024-05-05 00:06:04

你需要做的第一件事就是给你的圆加上一个布尔掩码。 然后您可以将其应用于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)

相关问题 更多 >