簡體   English   中英

使用極坐標在matplotlib中繪制輪廓密度圖

[英]Contour density plot in matplotlib using polar coordinates

從一組角度(θ)和半徑(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')

這給了我這個數字

我現在想在其上繪制密度等值線圖,所以我試過:

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

這給了我以下結果,顯然不是我想做的。

我究竟做錯了什么 ?

我認為你的問題的解決方案是為你的直方圖定義二進制數組(例如,對於theta,在0到2pi之間的linspaced數組,對於r,在0到1之間)。 這可以使用函數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()

這應該導致

極坐標

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM