matplotlib:如何使用 fill_between 在雷达图中绘制闭合环? (我的尝试留下了空白。)

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

我正在尝试在雷达图中使用 fill_between 绘制“环”,遵循此处的 matplotlib 雷达示例: https://matplotlib.org/3.1.0/gallery/specialty_plots/radar_chart.html

我保留 radar_factory 函数不变,除了一个额外的重载函数“fill_between”,遵循示例中已经存在的“fill”示例:

def fill_between(self, *args, closed=True, **kwargs):
    """Override fill_between so that lines are closed by default"""
    return super().fill_between(closed=closed, *args, **kwargs)

据我了解,这应该将 closed=True 传递给 PolyCollection 对象。然而并没有。

这是重现问题的代码。它比最小的要长一点,但我认为与 matplotlib 文档中的示例保持接近很重要:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D

def radar_factory(num_vars, frame='circle'):
    # calculate evenly-spaced axis angles
    theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)

    class RadarAxes(PolarAxes):
        name = 'radar'
        # use 1 line segment to connect specified points
        RESOLUTION = 1

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # rotate plot such that the first axis is at the top
            self.set_theta_zero_location('N')

        def fill(self, *args, closed=True, **kwargs):
            """Override fill so that line is closed by default"""
            return super().fill(closed=closed, *args, **kwargs)

        def fill_between(self, *args, closed=True, **kwargs):
            """
            Override fill_between so that lines are closed by default
            - CUSTOM ADDITION TO EXAMPLE - 
            """
            return super().fill_between(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super().plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            # FIXME: markers at x[0], y[0] get doubled-up
            if x[0] != x[-1]:
                x = np.concatenate((x, [x[0]]))
                y = np.concatenate((y, [y[0]]))
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(np.degrees(theta), labels)

        def _gen_axes_patch(self):
            # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
            # in axes coordinates.
            if frame == 'circle':
                return Circle((0.5, 0.5), 0.5)
            elif frame == 'polygon':
                return RegularPolygon((0.5, 0.5), num_vars,
                                      radius=.5, edgecolor="k")
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

        def _gen_axes_spines(self):
            if frame == 'circle':
                return super()._gen_axes_spines()
            elif frame == 'polygon':
                # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
                spine = Spine(axes=self,
                              spine_type='circle',
                              path=Path.unit_regular_polygon(num_vars))
                # unit_regular_polygon gives a polygon of radius 1 centered at
                # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
                # 0.5) in axes coordinates.
                spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
                                    + self.transAxes)
                return {'polar': spine}
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

    register_projection(RadarAxes)
    return theta

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, y1=data1, y2=data2, color='red')
    ax.fill(theta, data1, facecolor='blue', alpha=0.25)
    ax.set_varlabels(spoke_labels)

    plt.show()

及其输出。我希望红色区域会效仿蓝色区域并填充整个多边形。

如何关闭红色间隙?

这是我评论中建议的解决方案,它依赖于您提供 xy1y2 作为 args,而不是 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()

示例输出:

如果需要,您也可以轻松实现 kwargs 解析以获得更大的灵活性,但显然,您失去了 matplotlib 解析的一些灵活性。但是,如果作为 len N 的 arg 或 len N+1 的 kwarg 提供,它仍然会解析 where:

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

输出: