【问题标题】:Contour density plot in matplotlib using polar coordinatesmatplotlib中使用极坐标的等高线密度图
【发布时间】:2016-10-30 09:47:37
【问题描述】:

从一组角度 (theta) 和半径 (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.

我做错了什么?

【问题讨论】:

  • 您能否举例说明密度等高线图的外观,对不起,我不是图形专家。
  • 这是一个图形,表示给定区域内点的平均密度,等高线划分不同密度的区域:i.stack.imgur.com/XJYnz.png
  • 为了得到类似的东西,你必须使用 pcolor 而不是 contourf?
  • 我都试过了,这并没有改变我的极坐标问题。

标签: python matplotlib polar-coordinates


【解决方案1】:

我认为解决您的问题的方法是为您的直方图定义 bins 数组(例如,在 0 和 2pi 之间为 theta 和在 0 和 1 之间为 r 的 linspaced 数组)。这可以通过函数 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()

结果应该是

【讨论】:

  • 你现在是否有办法让地块上各处的 bin 密度相同?到目前为止,中心的 bin 具有较小的表面,边界处的 bin 是否具有较大的表面。
  • 您可以使用非线性 bin 空间,以便每个 bin 的表面相同。或者,您可以使用直方图函数的 density=True 参数(或将 H 的内容除以每个 bin 的表面,这应该是等效的)
猜你喜欢
  • 2015-09-12
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2016-08-17
  • 2019-07-31
相关资源
最近更新 更多