如何在matplotlib中绘制极性hist2d / hexbin?

时间:2016-12-17 11:35:57

标签: matplotlib histogram scatter-plot polar-coordinates

我有一个随机向量(随机长度和随机角度),并希望通过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似乎是相关的(结果图像符合预期),但它看起来很混乱。

1 个答案:

答案 0 :(得分: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()

结果:

enter image description here

请注意,直方图尚未通过bin的区域进行归一化,这在极坐标中不是常数。靠近原点,箱子很小,所以其他一些网格可能更好。