如何在Python中制作极坐标网格剖面图

时间:2018-06-19 05:45:44

标签: python matplotlib

我想创建一个如下图所示的图表。


上面的图片来自周K.-J.等。 2014年关于电离层的离子上升。
当我尝试类似的东西时:

import matplotlib.pyplot as plt
import numpy as np

thetabin=36
rbin=0.5
rmin=6
rmax=12
rmin=rmin+rbin
r_arr=linspace(rmin,rmax,(rmax-rmin)/rbin+1)
theta_arr=linspace(0,360,thetabin+1)
C = rand(len(r_arr), len(theta_arr))

plt.pcolor(r_arr,theta_arr,C.T)
xlabel(r'r')
ylabel(r'theta')
plt.show()

我只得到这张矩形图片:

enter image description here

我怎样才能把它变成一个饼图风格的'图片?

2 个答案:

答案 0 :(得分:2)

所以你的代码几乎就在那里,但缺少三件事:

  1. 你需要使用一个极地'投影。这告诉pyplot您正在使用极坐标,因此它将创建一个圆形图,就像您链接的图像一样。
  2. 你的theta数组需要是弧度,而不是度数。
  3. 包含r和theta值的数组需要是2D而不是1D。
  4. 我创建了一个代码的工作版本,并将其包含在下面:

        import matplotlib.pyplot as plt
        import numpy as np
    
        # number of bins in r and theta dimensions
        N_bins_theta = 36
        N_bins_r = 10
    
        # limits in r dimension
        rmin = 6
        rmax = 12
    
        # setting up 1D arrays in r and theta
        r = np.linspace(rmin, rmax, N_bins_r)
        theta = np.linspace(0, 2*np.pi, N_bins_theta)  # N.B. radians not degrees
    
        # 'gridding' the 1D arrays into 2D arrays so they can be used by pcolor
        theta, r = np.meshgrid(theta, r)
    
        # generating random data; note shape of array
        C = np.random.rand(N_bins_r, N_bins_theta)
    
        # setting up 'polar' projection and plotting
        ax = plt.subplot(111, projection='polar')
        plt.pcolor(theta, r, C)
        plt.show()
    

    这是图像输出:

    A working polar plot

答案 1 :(得分:0)

projection='polar'解决方案的美学不满意,我写了另一种解决方案。它利用自定义例程绘制环形扇区。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

COLORMAP = 'jet'        # choose colors here

def polar_annular_sector(r1, r2, theta1, theta2, **kargs):
    # draw annular sector in polar coordinates
    theta = np.arange(theta1, theta2+1, 1)/180.*np.pi
    cr1 = np.full_like(theta, r1)
    cr2 = np.full_like(theta, r2)
    plt.fill_between(theta, cr1, cr2, **kargs)

r_min=0
r_max=40
r_step = 5
r_arr = np.linspace(r_min,r_max-r_step,(r_max-r_min)/r_step)

theta_step = 15
theta_arr = np.linspace(0,360-theta_step,360/theta_step)

# generate random data
C = np.random.rand(len(r_arr), len(theta_arr))

# load colormap
space = np.linspace(0.0, 1.0, 100)
rgb = cm.get_cmap(COLORMAP)(space)[np.newaxis, :, :3]

# draw custom (slow) polar mesh profile
plt.polar()
for ri, r in enumerate(r_arr):
    print (ri, r)
    for ti, th in enumerate(theta_arr):
        color = rgb[0, int(C[ri, ti]*len(space))]
        polar_annular_sector(r, r+r_step, th, th+theta_step, color=color)
plt.show()

抽样结果:

Color mesh in a circle

另一个(12 x 36):

Color mesh in a doughnut

相关问题