poisso commited on
Commit
889c9b7
·
1 Parent(s): 5f2abf2

add radar chart module

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