【问题标题】:How to draw polar hist2d/hexbin in matplotlib?如何在 matplotlib 中绘制极坐标 hist2d/hexbin?
【发布时间】:2017-05-03 01:29:53
【问题描述】:

我有一个随机向量(随机长度和随机角度),并想通过hist2dhexbin 绘制其近似 PDF(概率密度函数)。不幸的是,它们似乎不适用于极坐标图,以下代码一无所获:

import numpy as np
import matplotlib.pyplot as plt

# Generate random data:
N = 1024
r = .5 + np.random.normal(size=N, scale=.1)
theta = np.pi / 2 + np.random.normal(size=N, scale=.1)

# Plot:
ax = plt.subplot(111, polar=True)
ax.hist2d(theta, r)
plt.savefig('foo.png')
plt.close()

我希望它看起来像这样:pylab_examples example code: hist2d_demo.py 仅在极坐标中。迄今为止最接近的结果是彩色散点图为adviced here

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate random data:
N = 1024
r = .5 + np.random.normal(size=N, scale=.1)
theta = np.pi / 2 + np.random.normal(size=N, scale=.1)

# Plot:
ax = plt.subplot(111, polar=True)

# Using approach from:
# https://stackoverflow.com/questions/20105364/how-can-i-make-a-scatter-plot-colored-by-density-in-matplotlib
theta_r = np.vstack([theta,r])
z = gaussian_kde(theta_r)(theta_r)

ax.scatter(theta, r, c=z, s=10, edgecolor='')

plt.savefig('foo.png')
plt.close()

Image from the second version of the code

有没有更好的方法让它更像使用 hist2d 生成的真实 PDF? This question 似乎是相关的(生成的图像符合预期),但看起来很乱。

【问题讨论】:

    标签: matplotlib histogram scatter-plot polar-coordinates


    【解决方案1】:

    使用pcolormesh 的一种方法:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.stats import gaussian_kde
    
    # Generate random data:
    N = 10000
    r = .5 + np.random.normal(size=N, scale=.1)
    theta = np.pi / 2 + np.random.normal(size=N, scale=.1)
    
    
    # Histogramming
    nr = 50
    ntheta = 200
    r_edges = np.linspace(0, 1, nr + 1)
    theta_edges = np.linspace(0, 2*np.pi, ntheta + 1)
    H, _, _ = np.histogram2d(r, theta, [r_edges, theta_edges])
    
    # Plot
    ax = plt.subplot(111, polar=True)
    Theta, R = np.meshgrid(theta_edges, r_edges)
    ax.pcolormesh(Theta, R, H)
    plt.show()
    

    结果:

    请注意,直方图尚未通过 bin 区域进行归一化,该区域在极坐标中不是恒定的。靠近原点,bin 非常小,因此其他类型的网格划分可能会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      相关资源
      最近更新 更多