使用极坐标在matplotlib中绘制轮廓密度图

时间:2016-10-30 09:47:38

标签: python matplotlib polar-coordinates

从一组角度(θ)和半径(r)我使用matplotlib绘制散点图:

fig = plt.figure()
ax = plt.subplot(111, polar=True)

ax.scatter(theta, r, color='None', edgecolor='red')

ax.set_rmax(1)   
plt.savefig("polar.eps",bbox_inches='tight')

Which gave me this figure

我现在想在其上绘制密度等值线图,所以我尝试了:

fig = plt.figure()
ax = plt.subplot(111, polar=True)

H, theta_edges, r_edges = np.histogram2d(theta, r)
cax = ax.contourf(theta_edges[:-1], r_edges[:-1], H, 10, cmap=plt.cm.Spectral)

ax.set_rmax(1)
plt.savefig("polar.eps",bbox_inches='tight')

Which gave me the following results that is obviously not what I wanted to do.

我做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为你的问题的解决方案是为你的直方图定义二进制数组(例如,对于theta,在0到2pi之间的linspaced数组,对于r,在0到1之间)。这可以通过函数numpy.histogram

的bin或range参数来完成

我这样做,通过绘制theta%(2 * pi)而不是theta来确保theta值都在0到2pi之间。

最后,您可以选择绘制bin边缘的中间而不是bin的左侧,如示例所示(使用0.5 *(r_edges [1:] + r_edges [: - 1])而不是r_edges [:-1])

以下是代码

的建议
import matplotlib.pyplot as plt
import numpy as np

#create the data 
r1     = .2 + .2 * np.random.randn(200)
theta1 = 0. + np.pi / 7. * np.random.randn(len(r1)) 
r2     = .8 + .2 * np.random.randn(300)
theta2 = .75 * np.pi + np.pi / 7. * np.random.randn(len(r2)) 
r = np.concatenate((r1, r2))
theta = np.concatenate((theta1, theta2))



fig = plt.figure()
ax = plt.subplot(111, polar=True)

#define the bin spaces
r_bins     = np.linspace(0., 1., 12)
N_theta    = 36
d_theta    = 2. * np.pi / (N_theta + 1.)
theta_bins = np.linspace(-d_theta / 2., 2. * np.pi + d_theta / 2., N_theta)


H, theta_edges, r_edges = np.histogram2d(theta % (2. * np.pi), r, bins = (theta_bins, r_bins))

#plot data in the middle of the bins
r_mid     = .5 * (r_edges[:-1] + r_edges[1:])
theta_mid = .5 * (theta_edges[:-1] + theta_edges[1:])


cax = ax.contourf(theta_mid, r_mid, H.T, 10, cmap=plt.cm.Spectral)
ax.scatter(theta, r, color='k', marker='+')
ax.set_rmax(1)
plt.show()

应该以

结果

polar histogram