问题是你只是在转换数组的边。通过只转换边的x和y坐标,可以有效地转换二维数组中对角线的坐标。这一行的theta值的范围非常小,您将该范围应用于整个网格。在
快速(但不正确)的修复
在大多数情况下,您可以将整个网格(即x和y的二维数组,生成theta和{}的二维数组)转换为极坐标。在
而不是:H, xedges, yedges = np.histogram2d(x2,y2)
theta_edges, r_edges = CartesianToPolar(xedges[:-1],yedges[:-1])
做类似于:
^{pr2}$
作为一个完整的例子:import numpy as np
import matplotlib.pyplot as plt
def main():
x2, y2 = generate_data()
theta2, r2 = cart2polar(x2,y2)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, projection="polar")
ax2.scatter(theta2, r2, color='hotpink')
H, xedges, yedges = np.histogram2d(x2,y2)
xedges, yedges = np.meshgrid(xedges[:-1], yedges[:-1])
theta_edges, r_edges = cart2polar(xedges, yedges)
ax2.contour(theta_edges, r_edges, H)
plt.show()
def generate_data():
np.random.seed(2015)
N = 1000
shift_value = -6.
x2 = np.random.randn(N) + shift_value
y2 = np.random.randn(N) + shift_value
return x2, y2
def cart2polar(x,y):
r = np.sqrt(x**2 + y**2)
theta = np.arctan2(y,x)
return theta, r
main()
但是,您可能会注意到这看起来有点不正确。这是因为ax.contour隐式地假设输入数据在规则网格上。我们在笛卡尔坐标系下给了它一个规则网格,但在极坐标系中没有给它一个规则网格。假设我们在极坐标系中通过了一个规则的网格。我们可以重新取样,但有更简单的方法。在
正确的解决方案
要正确绘制二维直方图,请在极坐标空间中计算直方图。在
例如,执行类似的操作:theta2, r2 = cart2polar(x2,y2)
H, theta_edges, r_edges = np.histogram2d(theta2, r2)
ax2.contour(theta_edges[:-1], r_edges[:-1], H)
作为一个完整的例子:import numpy as np
import matplotlib.pyplot as plt
def main():
x2, y2 = generate_data()
theta2, r2 = cart2polar(x2,y2)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, projection="polar")
ax2.scatter(theta2, r2, color='hotpink')
H, theta_edges, r_edges = np.histogram2d(theta2, r2)
ax2.contour(theta_edges[:-1], r_edges[:-1], H)
plt.show()
def generate_data():
np.random.seed(2015)
N = 1000
shift_value = -6.
x2 = np.random.randn(N) + shift_value
y2 = np.random.randn(N) + shift_value
return x2, y2
def cart2polar(x,y):
r = np.sqrt(x**2 + y**2)
theta = np.arctan2(y,x)
return theta, r
main()
最后,您可能会注意到上面的结果有轻微的变化。这与面向单元格的网格约定(x[0,0], y[0,0]表示单元格的中心)和面向边缘的网格约定(x[0,0], y[0,0]给出单元格的左下角)有关。ax.contour希望内容以单元格为中心,但您给了它边缘对齐的x和y值。在
这只是半个单元的移位,但如果您想修复它,请执行以下操作:def centers(bins):
return np.vstack([bins[:-1], bins[1:]]).mean(axis=0)
H, theta_edges, r_edges = np.histogram2d(theta2, r2)
theta_centers, r_centers = centers(theta_edges), centers(r_edges)
ax2.contour(theta_centers, r_centers, H)