Home > database >  matplotlib: How to plot a closed ring in a radar plot using fill_between? (My attempt leaves a gap.)
matplotlib: How to plot a closed ring in a radar plot using fill_between? (My attempt leaves a gap.)

Time:03-23

I'm attempting to use fill_between in a radar plot to paint a "ring", following the matplotlib radar example here: Output of above code

CodePudding user response:

Here is a solution as suggested in my comment that relies on you providing x, y1, and y2 as args, not kwargs:

....
def fill_between(self, *args, **kwargs):
    """
    Override fill_between 
    - CUSTOM ADDITION TO EXAMPLE - 
    """
    if len(args) and args[0][0] != args[0][-1]:
        args = list(args)
        for i, arg in enumerate(args):
            args[i] = np.append(arg, arg[0])            
                              
    return super().fill_between(*args, **kwargs)
....

....
if __name__ == '__main__':
    N = 5
    theta = radar_factory(N, frame='polygon')

    data1 = [2,1.5,3,3,2]
    data2 = [1,0.5,2,2,1]
    spoke_labels = ['A', 'B', 'C', 'D', 'E']

    fig, ax = plt.subplots(figsize=(9, 9), nrows=1, ncols=1,
                             subplot_kw=dict(projection='radar'))

    ax.plot(theta, data1, color='blue')
    ax.plot(theta, data2, color='blue')
    ax.fill_between(theta, data1, data2, color='red')
    ax.fill(theta, data2, facecolor='blue', alpha=0.25)
    ax.set_varlabels(spoke_labels)

    plt.show()

Sample output: enter image description here

You can easily implement also kwargs parsing for greater flexibility if needed but obviously, you lose some flexibility of matplotlib parsing. However, it still parses where if provided as arg of len N or kwarg of len N 1:

#where array provided as arg of len N
ax.fill_between(theta, data1, data2, [True, True, False, True, True], color='red')    
#or as kwarg of len N 1
#ax.fill_between(theta, data1, data2, where=[True, True, False, True, True, True], color='red')

Output: enter image description here

  • Related