极坐标轮廓图 - 装箱形状不匹配

时间:2015-08-05 00:03:39

标签: python numpy matplotlib contour

我想绘制从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),区间为13,对于天顶(0-180),区间为7。 histogram2d函数返回的矩阵具有(12,6)的形状,因为这是边缘之间的槽数。我只是不确定如何修复分档。

1 个答案:

答案 0 :(得分:1)

一种方法是将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()

enter image description here