我有一个二维数组,它表示极坐标系中位置的函数值。例如:
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)
这里排列在对应于极坐标的矩形网格中。我想重新排列数组中的数据,以便轴表示相应的笛卡尔坐标系。新旧布局可以按如下方式可视化: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)
这里明确给出了坐标,并相应地调整了绘图。我希望在数据数组本身中重新排列数据。它应该包含所有值,可以选择用零填充以适合形状(类似于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')
有没有办法在实现转换的同时避免结果数据数组中的空白区域?
胡说叔叔
温温酱
慕斯王
相关分类