Search code examples
pythonmatplotlibplotpolar-coordinates

matplotlib: fill circular sector between two curves in a polar plot


So I have two curves theta1(r) and theta2(r), where r is uniformly spaced between some two numbers (1 and 330 in this case). How can I fill the radial segment between the two curves?

I have considered adapting this solution, but it does not seem useful out of the box. Provided solution relies on an inverse relation, r(theta), which would be ambiguous and thus inapplicable in my case.

enter image description here


Solution

  • One option is to make a Polygon of the circular sector

    import matplotlib.pyplot as plt
    from matplotlib.patches import Polygon
    import numpy as np
    
    
    fig, ax = plt.subplots(subplot_kw=dict(projection="polar"))
    
    n = 330
    r = np.arange(330)
    
    # auto correlate random numbers (see comment below)
    a = np.zeros(n) + np.add.accumulate(np.random.normal(0, np.pi / 180, size=n))
    b = np.ones(n) * np.pi / 2 + np.add.accumulate(np.random.normal(0, np.pi / 180, size=n))
    
    ax.plot(a, r)
    ax.plot(b, r)
    
    arc_theta = np.linspace(a[-1], b[-1], 101)
    arc_r = np.ones_like(arc_theta) * 330
    
    start = np.c_[a, r]
    arc = np.c_[arc_theta, arc_r]
    end = np.c_[b, r][::-1]
    
    verts = np.concatenate([start, arc, end])
    
    p = Polygon(verts, fc="purple", alpha=0.5)
    ax.add_artist(p)
    
    plt.show()
    

    gives

    enter image description here