1"""
2======================================
3Radar chart (aka spider or star chart)
4======================================
5
6This example creates a radar chart, also known as a spider or star chart [1]_.
7
8Although this example allows a frame of either 'circle' or 'polygon', polygon
9frames don't have proper gridlines (the lines are circles instead of polygons).
10It's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in
11matplotlib.axis to the desired number of vertices, but the orientation of the
12polygon is not aligned with the radial axes.
13
14.. [1] http://en.wikipedia.org/wiki/Radar_chart
15"""
16
17import numpy as np
18
19import matplotlib.pyplot as plt
20from matplotlib.patches import Circle, RegularPolygon
21from matplotlib.path import Path
22from matplotlib.projections.polar import PolarAxes
23from matplotlib.projections import register_projection
24from matplotlib.spines import Spine
25from matplotlib.transforms import Affine2D
26
27
28def radar_factory(num_vars, frame='circle'):
29    """
30    Create a radar chart with `num_vars` axes.
31
32    This function creates a RadarAxes projection and registers it.
33
34    Parameters
35    ----------
36    num_vars : int
37        Number of variables for radar chart.
38    frame : {'circle', 'polygon'}
39        Shape of frame surrounding axes.
40
41    """
42    # calculate evenly-spaced axis angles
43    theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)
44
45    class RadarAxes(PolarAxes):
46
47        name = 'radar'
48        # use 1 line segment to connect specified points
49        RESOLUTION = 1
50
51        def __init__(self, *args, **kwargs):
52            super().__init__(*args, **kwargs)
53            # rotate plot such that the first axis is at the top
54            self.set_theta_zero_location('N')
55
56        def fill(self, *args, closed=True, **kwargs):
57            """Override fill so that line is closed by default"""
58            return super().fill(closed=closed, *args, **kwargs)
59
60        def plot(self, *args, **kwargs):
61            """Override plot so that line is closed by default"""
62            lines = super().plot(*args, **kwargs)
63            for line in lines:
64                self._close_line(line)
65
66        def _close_line(self, line):
67            x, y = line.get_data()
68            # FIXME: markers at x[0], y[0] get doubled-up
69            if x[0] != x[-1]:
70                x = np.append(x, x[0])
71                y = np.append(y, y[0])
72                line.set_data(x, y)
73
74        def set_varlabels(self, labels):
75            self.set_thetagrids(np.degrees(theta), labels)
76
77        def _gen_axes_patch(self):
78            # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
79            # in axes coordinates.
80            if frame == 'circle':
81                return Circle((0.5, 0.5), 0.5)
82            elif frame == 'polygon':
83                return RegularPolygon((0.5, 0.5), num_vars,
84                                      radius=.5, edgecolor="k")
85            else:
86                raise ValueError("Unknown value for 'frame': %s" % frame)
87
88        def _gen_axes_spines(self):
89            if frame == 'circle':
90                return super()._gen_axes_spines()
91            elif frame == 'polygon':
92                # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
93                spine = Spine(axes=self,
94                              spine_type='circle',
95                              path=Path.unit_regular_polygon(num_vars))
96                # unit_regular_polygon gives a polygon of radius 1 centered at
97                # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
98                # 0.5) in axes coordinates.
99                spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
100                                    + self.transAxes)
101                return {'polar': spine}
102            else:
103                raise ValueError("Unknown value for 'frame': %s" % frame)
104
105    register_projection(RadarAxes)
106    return theta
107
108
109def example_data():
110    # The following data is from the Denver Aerosol Sources and Health study.
111    # See doi:10.1016/j.atmosenv.2008.12.017
112    #
113    # The data are pollution source profile estimates for five modeled
114    # pollution sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical
115    # species. The radar charts are experimented with here to see if we can
116    # nicely visualize how the modeled source profiles change across four
117    # scenarios:
118    #  1) No gas-phase species present, just seven particulate counts on
119    #     Sulfate
120    #     Nitrate
121    #     Elemental Carbon (EC)
122    #     Organic Carbon fraction 1 (OC)
123    #     Organic Carbon fraction 2 (OC2)
124    #     Organic Carbon fraction 3 (OC3)
125    #     Pyrolized Organic Carbon (OP)
126    #  2)Inclusion of gas-phase specie carbon monoxide (CO)
127    #  3)Inclusion of gas-phase specie ozone (O3).
128    #  4)Inclusion of both gas-phase species is present...
129    data = [
130        ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],
131        ('Basecase', [
132            [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],
133            [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],
134            [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],
135            [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],
136            [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]),
137        ('With CO', [
138            [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],
139            [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],
140            [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],
141            [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],
142            [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]),
143        ('With O3', [
144            [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],
145            [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],
146            [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],
147            [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],
148            [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]),
149        ('CO & O3', [
150            [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],
151            [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],
152            [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],
153            [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],
154            [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]])
155    ]
156    return data
157
158
159if __name__ == '__main__':
160    N = 9
161    theta = radar_factory(N, frame='polygon')
162
163    data = example_data()
164    spoke_labels = data.pop(0)
165
166    fig, axs = plt.subplots(figsize=(9, 9), nrows=2, ncols=2,
167                            subplot_kw=dict(projection='radar'))
168    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
169
170    colors = ['b', 'r', 'g', 'm', 'y']
171    # Plot the four cases from the example data on separate axes
172    for ax, (title, case_data) in zip(axs.flat, data):
173        ax.set_rgrids([0.2, 0.4, 0.6, 0.8])
174        ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
175                     horizontalalignment='center', verticalalignment='center')
176        for d, color in zip(case_data, colors):
177            ax.plot(theta, d, color=color)
178            ax.fill(theta, d, facecolor=color, alpha=0.25)
179        ax.set_varlabels(spoke_labels)
180
181    # add legend relative to top-left plot
182    labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
183    legend = axs[0, 0].legend(labels, loc=(0.9, .95),
184                              labelspacing=0.1, fontsize='small')
185
186    fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
187             horizontalalignment='center', color='black', weight='bold',
188             size='large')
189
190    plt.show()
191
192
193#############################################################################
194#
195# .. admonition:: References
196#
197#    The use of the following functions, methods, classes and modules is shown
198#    in this example:
199#
200#    - `matplotlib.path`
201#    - `matplotlib.path.Path`
202#    - `matplotlib.spines`
203#    - `matplotlib.spines.Spine`
204#    - `matplotlib.projections`
205#    - `matplotlib.projections.polar`
206#    - `matplotlib.projections.polar.PolarAxes`
207#    - `matplotlib.projections.register_projection`
208