极地等高线图 - 合并形状不匹配

Polar Contour Plot - binning shape mismatch

我想绘制从 XYZ 数据获得的方位角和天顶角的极地等值线图。但是我传递给 contourf 函数的数组是畸形的,我不确定如何更正它?

import numpy as np
import matplotlib.pyplot as plt

# Populated arrays with angles.
azimuths = np.random.random(200)*360
zeniths = np.random.random(200)*180

a_bins = np.linspace(0,360,13)
z_bins = np.linspace(0,180,7)

grid, ae, ze = np.histogram2d(azimuths, zeniths, bins=[a_bins,z_bins])

a_bins = np.radians(a_bins)
r, theta = np.meshgrid(z_bins, a_bins)

# Plot
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
cax = ax.contourf(theta, r, grid, 30)
cb = fig.colorbar(cax)

plt.show()

代码运行但抛出以下警告:x 的形状与 z 的形状不匹配:找到 (13, 7) 而不是 (12, 6)。

现在我想我明白了错误。方位角 (0-360) 的 bin 为 13,天顶 (0-180) 的 bin 为 7。 histogram2d 函数返回的矩阵的形状为 (12,6),因为这是边之间的槽数。我只是不确定如何修复分箱。

一种方法是将 grid 数组扩展为与 thetar 相同的形状。这是必要的,以便极坐标图一直延伸(并匹配 theta=0

import numpy as np
import matplotlib.pyplot as plt

# Populated arrays with angles.
azimuths = np.random.random(200)*360
zeniths = np.random.random(200)*180

a_bins = np.linspace(0,360,13)
z_bins = np.linspace(0,180,7)

grid, ae, ze = np.histogram2d(azimuths, zeniths, bins=[a_bins,z_bins])

a_bins = np.radians(a_bins)
r, theta = np.meshgrid(z_bins, a_bins)

# Extend grid by one column row, using the 0th column and row
g = np.zeros(r.shape)
g[:-1,:-1] = grid 
g[-1] = g[0]      # copy the top row to the bottom
g[:,-1] = g[:,0]  # copy the left column to the right
print g.shape,r.shape,theta.shape
### (13, 7) (13, 7) (13, 7)

# Plot
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
cax = ax.contourf(theta, r, g, 30)
cb = fig.colorbar(cax)

plt.show()