首页 文章

Matplotlib中的极坐标等高线图

提问于
浏览
8

我有一组数据要用于使用Matplotlib在极坐标中生成等高线图 .

我的数据如下:

  • theta - 1D角度值数组

  • radius - 半径值的一维数组

  • value - 我要用于轮廓的一维值数组

这些都是正确对齐的一维数组 - 例如:

theta   radius   value
30      1        2.9
30      2        5.3
35      5        9.2

也就是说,所有的值都重复了足够的次数,以便三个变量的这个“表”的每一行定义一个点 .

如何根据这些值创建极坐标轮廓图?我已经考虑过将半径和θ值转换为x和y值并在笛卡尔坐标中进行,但轮廓函数似乎需要2D数组,我不太明白为什么 .

有任何想法吗?

2 回答

  • 3

    我不能直接绘制极坐标轮廓图,但如果转换为笛卡尔坐标,则可以使用griddata函数将1D阵列转换为2D .

  • 8

    Matplotlib的 contour() 函数要求将数据排列为点的2D网格以及每个网格点的相应网格值 . 如果您的数据自然排列在网格中,您可以将r,theta转换为x,y并使用 contour(r*np.cos(theta), r*np.sin(theta), values) 来制作您的绘图 .

    如果您的数据不是't naturally gridded, you should follow Stephen'的建议,并使用 griddata() 将数据插入到网格中 .

    以下脚本显示了两者的示例 .

    import pylab as plt
    from matplotlib.mlab import griddata
    import numpy as np
    
    # data on a grid
    r = np.linspace(0, 1, 100)
    t = np.linspace(0, 2*np.pi, 100)
    r, t = np.meshgrid(r, t)
    z = (t-np.pi)**2 + 10*(r-0.5)**2
    
    plt.subplot(121)
    plt.contour(r*np.cos(t), r*np.sin(t), z)
    
    # ungrid data, then re-grid it
    r = r.flatten()
    t = t.flatten()
    x = r*np.cos(t)
    y = r*np.sin(t)
    z = z.flatten()
    xgrid = np.linspace(x.min(), x.max(), 100)
    ygrid = np.linspace(y.min(), y.max(), 100)
    xgrid, ygrid = np.meshgrid(xgrid, ygrid)
    zgrid = griddata(x,y,z, xgrid, ygrid)
    
    plt.subplot(122)
    plt.contour(xgrid, ygrid, zgrid)
    
    plt.show()
    

    enter image description here

相关问题