2016-12-17 7 views
2

私はランダムなベクトル(ランダムな長さとランダムな角度)を持っており、その近似PDF(確率密度関数)をhist2dまたはhexbinでプロットしたいと考えています。のみ極座標でpylab_examples example code: hist2d_demo.py:私はこのように見えるためにそれをしたいと思いmatplotlibにpolar hist2d/hexbinを描画する方法は?

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

:残念ながら、彼らは極プロットでは動作しないようです、次のコードは何も得ていません。最寄りの結果は、これまで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は関連性があるようです(結果として得られる画像は期待どおりです)。 pcolormeshを使用して、これに

答えて

0

一つの方法:

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

注意座標。原点の近くでは、ビンはかなり小さいので、他の種類のメッシュが良いかもしれません。