-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathradar_plots.py
278 lines (208 loc) · 8.87 KB
/
radar_plots.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 10 13:05:12 2021
@author: morenodu
"""
# import numpy as np
# import matplotlib.pyplot as plt
# # Fixing random state for reproducibility
# def circle_clim(tmx,dtr,precip, scen_title):
# print(scen_title)
# # Compute pie slices
# np.random.seed(19680801)
# N = 3
# theta = np.array([0.523599,5*0.523599,4.71239])
# radii = np.array([tmx,dtr,precip])
# width = np.array([2.0944,2.0944,2.0944])
# cmap = plt.get_cmap("tab20c")
# outer_colors = cmap(np.arange(3)*4)
# ax = plt.subplot(111, projection='polar')
# ax.bar(theta, radii, width=width, bottom=0.0, color = ['k','b','r'], alpha=0.9)
# ax.set_rlabel_position(-135)
# ax.set_ylim(0,2000)
# ax.set_theta_zero_location('W')
# # ax.grid(False)
# # ax.spines['polar'].set_visible(True)
# # # ax.set_rticks([])
# ax.set_xticklabels([''])
# ax.set_title(f'Univariate occurance of 2012 analogues for {scen_title}')
# plt.tight_layout()
# plt.show()
# circle_clim(tmx = 43, dtr = 3, precip = 89, scen_title = 'PD' )
# circle_clim(tmx = 503, dtr = 3, precip = 165, scen_title = '2C')
# circle_clim(tmx = 1346, dtr = 0, precip = 241, scen_title = '3C')
# fig, ax = plt.subplots()
# size = 1
# vals = np.array([[120., 120.], [120., 120.], [120., 120.]])
# cmap = plt.get_cmap("tab20c")
# outer_colors = cmap(np.arange(3)*4)
# inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
# ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
# wedgeprops=dict(width=size, edgecolor='w'))
# ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,
# wedgeprops=dict(width=size, edgecolor='w'))
# ax.set(aspect="equal", title='Pie plot with `ax.pie`')
# plt.show()
#########################
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'):
"""Create a radar chart with `num_vars` axes.
This function creates a RadarAxes projection and registers it.
Parameters
----------
num_vars : int
Number of variables for radar chart.
frame : {'circle' | 'polygon'}
Shape of frame surrounding axes.
"""
# calculate evenly-spaced axis angles
theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)
class RadarAxes(PolarAxes):
name = 'radar'
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 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 draw(self, renderer):
""" Draw. If frame is polygon, make gridlines polygon-shaped """
if frame == 'polygon':
gridlines = self.yaxis.get_gridlines()
for gl in gridlines:
gl.get_path()._interpolation_steps = num_vars
super().draw(renderer)
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
#########################################
data = [['Tmx', 'Dtr', 'Precip'],
('Basecase', [[43, 4, 89],
[503, 3, 165],
[1346, 0, 241],])]
N = len(data[0])
theta = radar_factory(N, frame='circle')
spoke_labels = data.pop(0)
title, case_data = data[0]
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(projection='radar'))
fig.subplots_adjust(top=0.85, bottom=0.05)
ax.set_ylim(0,2000)
ax.set_rgrids([0, 500, 1000, 1500, 2000])
ax.set_title(title, position=(0.5, 1.1), ha='center')
for d in case_data:
line = ax.plot(theta, d)
ax.fill(theta, d, alpha=0.9)
ax.set_varlabels(spoke_labels)
plt.show()
def radar_plot_scen(tmx = 43, dtr = 3, precip = 89, scen_title = 'PD' ):
data = [['Tmx', 'Dtr', 'Precip'],
(f'Univariate occurance of 2012 analogues for {scen_title}', [[tmx, dtr, precip]])]
N = len(data[0])
theta = radar_factory(N, frame='circle')
spoke_labels = data.pop(0)
title, case_data = data[0]
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(projection='radar'))
fig.subplots_adjust(top=0.85, bottom=0.05)
ax.set_ylim(0,2000)
ax.set_rgrids([0, 500, 1000, 1500, 2000])
ax.set_title(title, position=(0.5, 1.1), ha='center')
for d in case_data:
line = ax.plot(theta, d)
ax.fill(theta, d, alpha=0.9)
ax.set_varlabels(spoke_labels)
return fig
fig_radar_PD = radar_plot_scen(tmx = 43, dtr = 3, precip = 89, scen_title = 'PD' )
fig_radar_2C = radar_plot_scen(tmx = 503, dtr = 3, precip = 165, scen_title = '2C')
fig_radar_3C = radar_plot_scen(tmx = 1346, dtr = 0, precip = 241, scen_title = '3C')
# Figure with 3 plots - Seasons exceeding 2012 conditions ########################################################
fig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(15, 5), dpi=500, subplot_kw=dict(projection='radar'))
fig.subplots_adjust(top=0.85, bottom=0.05)
# Subplot 1 - PD
data = [['Tmx', 'Dtr', 'Precip'], (f'a) PD scenario', [[43, 3, 89]])]
N = len(data[0])
theta = radar_factory(N, frame='circle')
spoke_labels = data.pop(0)
title, case_data = data[0]
ax1.set_ylim(0,2000)
ax1.set_rgrids([0, 500, 1000, 1500, 2000])
ax1.set_title(title, position=(0.5, 1.1), ha='center')
for d in case_data:
line = ax.plot(theta, d)
ax1.fill(theta, d, alpha=0.9)
ax1.set_varlabels(spoke_labels)
# Subplot 2 - 2C
data = [['Tmx', 'Dtr', 'Precip'], (f'b) 2C scenario', [[503, 3, 165]])]
N = len(data[0])
theta = radar_factory(N, frame='circle')
spoke_labels = data.pop(0)
title, case_data = data[0]
ax2.set_ylim(0,2000)
ax2.set_rgrids([500, 1000, 1500, 2000])
ax2.set_title(title, position=(0.5, 1.1), ha='center')
for d in case_data:
line = ax.plot(theta, d)
ax2.fill(theta, d, alpha=0.9)
ax2.set_varlabels(spoke_labels)
# Subplot 3 - 3C
data = [['Tmx', 'Dtr', 'Precip'], (f'c) 3C scenario', [[1346, 0, 241]])]
N = len(data[0])
theta = radar_factory(N, frame='circle')
spoke_labels = data.pop(0)
title, case_data = data[0]
ax3.set_ylim(0,2000)
ax3.set_rgrids([0, 500, 1000, 1500, 2000])
ax3.set_title(title, position=(0.5, 1.1), ha='center')
for d in case_data:
line = ax.plot(theta, d)
ax3.fill(theta, d, alpha=0.9)
ax3.set_varlabels(spoke_labels)
# plt.tight_layout()
fig.savefig('paper_figures/radar_2012_2.png', format='png', dpi=500)
#######################################