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

3

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

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')

这是给我的图形

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

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')
我得到了以下结果,显然不是我想要的。 我做错了什么?

你能否举个例子说明密度等高线图是什么样子的?抱歉,我不是一个图表专家。 - thesonyman101
1
这是一个图表,表示给定区域内点的平均密度,等高线勾画出不同密度的区域:http://i.stack.imgur.com/XJYnz.png - Phaune
为了得到类似的效果,您需要使用pcolor而不是contourf吗? - thesonyman101
1
我尝试了两种方法,但极坐标仍然存在问题。 - Phaune
1个回答

3
我认为解决你的问题的方法是为直方图定义bin数组(例如theta在0到2pi之间的线性间隔数组,r在0到1之间的数组)。可以使用numpy.histogram函数的bins或range参数来完成此操作。
如果这样做,请确保theta值都在0到2pi之间,方法是绘制theta %(2 * pi)而不是theta。
最后,您可以选择绘制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()

预期结果应该如下:

极坐标直方图


你知道是否有一种方法可以在图中使每个箱子的密度相同吗?目前,中心的箱子面积较小,而边界处的箱子面积较大。 - Phaune
1
您可以使用非线性的箱子空间,使得每个箱子的表面积相同。或者,您可以使用直方图函数的density=True参数(或将H的内容除以每个箱子的表面积,这应该是等效的)。 - user2660966

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接