根据从极坐标到笛卡尔坐标的变换重新排列二维数组中的数据

a_g*_*est 8 python numpy scipy coordinate-transformation polar-coordinates

我有一个二维数组,表示极坐标系中位置处的函数值。例如:

import numpy as np

radius = np.linspace(0, 1, 50)
angle = np.linspace(0, 2*np.pi, radius.size)
r_grid, a_grid = np.meshgrid(radius, angle)
data = np.sqrt((r_grid/radius.max())**2
               + (a_grid/angle.max())**2)
Run Code Online (Sandbox Code Playgroud)

这里的data排列在与极坐标相对应的矩形网格中。我想重新排列数组中的数据,使轴代表相应的笛卡尔坐标系。旧版与新版布局的可视化如下:

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=plt.figaspect(0.5))
ax1.set(title='Polar coordinates', xlabel='Radius', ylabel='Angle')
ax1.pcolormesh(r_grid, a_grid, data)
ax2.set(title='Cartesian coordinates', xlabel='X', ylabel='Y')
x_grid = r_grid * np.cos(a_grid)
y_grid = r_grid * np.sin(a_grid)
ax2.pcolormesh(x_grid, y_grid, data)
Run Code Online (Sandbox Code Playgroud)

例子

这里明确给出了坐标,并相应地调整了绘图。我希望将数据重新排列在数据数组本身中。它应该包含所有值,可以选择填充零以适应形状(类似于scipy.ndimage.rotate(..., reshape=True))。

如果我手动遍历极坐标数组来计算笛卡尔坐标,结果包含理想情况下也应该填充的空白区域:

new = np.zeros_like(data)
visits = np.zeros_like(new)
for r, a, d in np.nditer((r_grid, a_grid, data)):
    i = 0.5 * (1 + r * np.sin(a)) * new.shape[0]
    j = 0.5 * (1 + r * np.cos(a)) * new.shape[1]
    i = min(int(i), new.shape[0] - 1)
    j = min(int(j), new.shape[1] - 1)
    new[i, j] += d
    visits[i, j] += 1
new /= np.maximum(visits, 1)
ax2.imshow(new, origin='lower')
Run Code Online (Sandbox Code Playgroud)

示例尝试

有没有办法实现转换,同时避免结果数据数组中的空白区域?

Arn*_*rne 0

您可以循环笛卡尔数组,将每个网格点转换为极坐标,并通过极坐标网格数据的插值来近似函数值。不过,由于缺乏足够接近的数据,您可能仍希望将角区域留空。

我认为没有更好的方法,除非您当然可以访问原始函数。