Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

vizplots.py 25 KB

You have to be logged in to leave a comment. Sign In
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
  1. """
  2. Creates interactive visualizations for Exploratory Data Analysis using PyViz
  3. and produce publication quality figures using PyGMT!
  4. """
  5. import os
  6. import warnings
  7. import holoviews as hv
  8. import intake
  9. import numpy as np
  10. import pandas as pd
  11. import panel as pn
  12. import param
  13. import pygmt
  14. import tqdm
  15. import xarray as xr
  16. warnings.filterwarnings(
  17. action="ignore",
  18. message="The global colormaps dictionary is no longer considered public API.",
  19. )
  20. class IceSat2Explorer(param.Parameterized):
  21. """
  22. ICESat-2 rate of height change over time (dhdt) interactive dashboard.
  23. Built using HvPlot and Panel.
  24. Adapted from the "Panel-based Datashader dashboard" at
  25. https://examples.pyviz.org/datashader_dashboard/dashboard.html.
  26. See also https://github.com/holoviz/datashader/pull/676.
  27. """
  28. # Param Widgets that interactively control plot settings
  29. plot_variable = param.Selector(
  30. default="dhdt_slope", objects=["referencegroundtrack", "dhdt_slope", "h_corr"]
  31. )
  32. cycle_number = param.Integer(default=7, bounds=(2, 8))
  33. dhdt_range = param.Range(default=(1.0, 10.0), bounds=(0.0, 20.0))
  34. rasterize = param.Boolean(default=True)
  35. datashade = param.Boolean(default=False)
  36. def __init__(self, placename: str = "whillans_upstream", **kwargs):
  37. super().__init__(**kwargs)
  38. self.placename = placename
  39. # Load from intake data source
  40. # catalog = intake.cat.atlas_cat
  41. self.catalog: intake.catalog.local.YAMLFileCatalog = intake.open_catalog(
  42. os.path.join(os.path.dirname(__file__), "atlas_catalog.yaml")
  43. )
  44. self.source = self.catalog.icesat2dhdt(placename=self.placename)
  45. try:
  46. import cudf
  47. import hvplot.cudf
  48. self.df_ = cudf.read_parquet(self.source._urlpath)
  49. except ImportError:
  50. self.df_ = self.source.to_dask()
  51. # Setup default plot (dhdt_slope) and x/y axis limits
  52. self.plot: hv.core.spaces.DynamicMap = self.source.plot.dhdt_slope()
  53. self.startX, self.endX = self.plot.range("x")
  54. self.startY, self.endY = self.plot.range("y")
  55. def keep_zoom(self, x_range, y_range):
  56. self.startX, self.endX = x_range
  57. self.startY, self.endY = y_range
  58. @param.depends(
  59. "cycle_number", "plot_variable", "dhdt_range", "rasterize", "datashade"
  60. )
  61. def view(self) -> hv.core.spaces.DynamicMap:
  62. # Filter/Subset data to what's needed. Wait for
  63. # https://github.com/holoviz/hvplot/issues/72 to do it properly
  64. cond = np.logical_and(
  65. float(self.dhdt_range[0]) < abs(self.df_.dhdt_slope),
  66. abs(self.df_.dhdt_slope) < float(self.dhdt_range[1]),
  67. )
  68. if self.plot_variable == "h_corr":
  69. df_subset = self.df_.loc[cond].dropna(
  70. subset=[f"h_corr_{self.cycle_number}"]
  71. )
  72. else:
  73. df_subset = self.df_.loc[cond]
  74. # Create the plot! Uses plot_kwargs from catalog metdata
  75. # self.plot = getattr(source.plot, self.plot_variable)()
  76. self.source = self.catalog.icesat2dhdt(
  77. cycle=self.cycle_number, placename=self.placename
  78. )
  79. plot_kwargs = {
  80. "xlabel": self.source.metadata["fields"]["x"]["label"],
  81. "ylabel": self.source.metadata["fields"]["y"]["label"],
  82. **self.source.metadata["plot"],
  83. **self.source.metadata["plots"][self.plot_variable],
  84. }
  85. plot_kwargs.update(
  86. rasterize=self.rasterize, datashade=self.datashade, dynspread=self.datashade
  87. )
  88. self.plot = df_subset.hvplot(
  89. title=f"ICESat-2 Cycle {self.cycle_number} {self.plot_variable}",
  90. **plot_kwargs,
  91. )
  92. # Keep zoom level intact when changing the plot_variable
  93. self.plot = self.plot.redim.range(
  94. x=(self.startX, self.endX), y=(self.startY, self.endY)
  95. )
  96. self.plot = self.plot.opts(active_tools=["pan", "wheel_zoom"])
  97. rangexy = hv.streams.RangeXY(
  98. source=self.plot,
  99. x_range=(self.startX, self.endX),
  100. y_range=(self.startY, self.endY),
  101. )
  102. rangexy.add_subscriber(self.keep_zoom)
  103. return self.plot
  104. def widgets(self):
  105. _widgets = pn.Param(
  106. self.param,
  107. widgets={
  108. "plot_variable": pn.widgets.RadioButtonGroup,
  109. "cycle_number": pn.widgets.IntSlider,
  110. "dhdt_range": {"type": pn.widgets.RangeSlider, "name": "dhdt_range_±"},
  111. "rasterize": pn.widgets.Checkbox,
  112. "datashade": pn.widgets.Checkbox,
  113. },
  114. )
  115. return pn.Row(
  116. pn.Column(_widgets[0], _widgets[1], align="center"),
  117. pn.Column(_widgets[2], _widgets[3], align="center"),
  118. pn.Column(_widgets[4], _widgets[5], align="center"),
  119. )
  120. def plot_alongtrack(
  121. df: pd.DataFrame,
  122. regionname: str,
  123. rgtpair: str,
  124. elev_var: str = "h_corr",
  125. xatc_var: str = "x_atc",
  126. time_var: str = "utc_time",
  127. cycle_var: str = "cycle_number",
  128. spacing: str = "1000/5",
  129. oldtonew: bool = True,
  130. ) -> pygmt.Figure:
  131. """
  132. Plot 2D along track cross-section view of Ice Surface Elevation over Time.
  133. Uses PyGMT to produce the figure. The input table should look something like
  134. below (more columns can be present too).
  135. | cycle_number | x_atc | h_corr | utc_time |
  136. |--------------|-------|--------|---------------------|
  137. | 1 | 500 | 14 | 2020-01-01T01:12:34 |
  138. | 2 | 500 | 12 | 2020-04-01T12:23:45 |
  139. | 3 | 500 | 10 | 2020-07-01T23:34:56 |
  140. which will produce a plot similar to the following:
  141. Ice Surface Elevation over each ICESat-2 cycle at Some Ice Stream
  142. ^
  143. | Reference Ground Track 1234_pt3
  144. |
  145. | ----------------------------- --- Cycle 1 at 2020-01-01T01:12:34
  146. Elev | -.-.-.-.-.-.-.-.-.-.-.-.-.-.- -.- Cycle 2 at 2020-04-01T12:23:45
  147. | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ Cycle 3 at 2020-07-01T23:34:56
  148. |____________________________________________________________________>
  149. Along track x
  150. Parameters
  151. ----------
  152. df : pandas.DataFrame
  153. A table containing the ICESat-2 track data from multiple cycles. It
  154. should ideally have columns called 'x_atc', 'h_corr', 'utc_time' and
  155. 'cycle_number'.
  156. regionname : str
  157. A descriptive placename for the data (e.g. Some Ice Stream), to be used
  158. in the figure's main title.
  159. rgtpair : str
  160. The name of the referencegroundtrack pair being plotted (e.g. 1234_pt3),
  161. to be used in the figure's subtitle.
  162. elev_var : str
  163. The elevation column name to use from the table data, plotted on the
  164. vertical y-axis. Default is 'h_corr'.
  165. xatc_var : str
  166. The x along-track column name to use from the table data, plotted on the
  167. horizontal x-axis. Default is 'x_atc'.
  168. time_var : str
  169. The time-dimension column name to use from the table data, used to
  170. calculate the mean datetime for each track in every cycle. Default is
  171. 'utc_time'.
  172. cycle_var : str
  173. The column name from the table which is used to determine which time
  174. cycle each row/observation falls into. Default is 'cycle_number'.
  175. spacing : str
  176. Provide as 'dx/dy' increments, this is passed directly to `pygmt.info`
  177. and used to round up and down the x and y axis limits for a nicer plot
  178. frame. Default is '1000/5'.
  179. oldtonew : bool
  180. Determine the plot order (True: Cycle 1 -> Cycle n; False: Cycle n ->
  181. Cycle 1), useful when you want the legend to go one way or the other.
  182. For example, the default `oldtonew=True` is recommended when plotting
  183. decreasing elevation over time (i.e. lake draining). Set to False
  184. instead to reverse the order, recommended when plotting increasing
  185. elevation over time (i.e. lake filling).
  186. Returns
  187. -------
  188. fig : pygmt.Figure
  189. A pygmt Figure instance containing the along track plot which can be
  190. viewed using fig.show() or saved to a file using fig.savefig()
  191. """
  192. fig = pygmt.Figure()
  193. # Setup map frame, title, axis annotations, etc
  194. fig.basemap(
  195. projection="X30c/10c",
  196. region=pygmt.info(table=df[[xatc_var, elev_var]], spacing=spacing),
  197. frame=[
  198. rf'WSne+t"Ice Surface Elevation over each ICESat-2 cycle at {regionname}"',
  199. 'xaf+l"Along track x (m)"',
  200. 'yaf+l"Elevation (m)"',
  201. ],
  202. )
  203. fig.text(
  204. text=f"Reference Ground Track {rgtpair}",
  205. position="TC",
  206. offset="jTC0c/0.2c",
  207. verbose="q",
  208. )
  209. # Colors from https://colorbrewer2.org/#type=qualitative&scheme=Set1&n=9
  210. cycle_colors: dict = {
  211. 1: "#999999",
  212. 2: "#f781bf",
  213. 3: "#a65628",
  214. 4: "#ffff33",
  215. 5: "#ff7f00",
  216. 6: "#984ea3",
  217. 7: "#4daf4a",
  218. 8: "#377eb8",
  219. 9: "#e41a1c",
  220. }
  221. # Choose only cycles that need to be plotted, reverse order if requested
  222. cycles: list = sorted(df[cycle_var].unique(), reverse=not oldtonew)
  223. cycle_colors: dict = {cycle: cycle_colors[cycle] for cycle in cycles}
  224. # For each cycle, plot the height values (elev_var) along the track (xatc_var)
  225. for cycle, color in cycle_colors.items():
  226. df_ = df.query(expr=f"{cycle_var} == @cycle").copy()
  227. # Get x, y, time
  228. data = np.column_stack(tup=(df_[xatc_var], df_[elev_var]))
  229. time_nsec = df_[time_var].mean()
  230. time_sec = np.datetime_as_string(arr=time_nsec.to_datetime64(), unit="s")
  231. label = f'"Cycle {cycle} at {time_sec}"'
  232. # Plot data points
  233. fig.plot(data=data, style="c0.05c", color=color, label=label)
  234. # Plot line connecting points
  235. # fig.plot(data=data, pen=f"faint,{color},-", label=f'"+g-1l+s0.15c"')
  236. fig.legend(S=3, position="jBL+jBL+o0.2c", box="+gwhite+p1p")
  237. return fig
  238. def _plot_crossover_area(
  239. outline_points: str or pd.DataFrame,
  240. df: np.ndarray,
  241. fig: pygmt.Figure = None,
  242. plotsize: float = 8,
  243. cmap: str = "vik",
  244. elev_range: list = None,
  245. wsne: str = "SE",
  246. ):
  247. """"""
  248. fig = fig or pygmt.Figure()
  249. plotregion: np.ndarray = pygmt.info(outline_points, per_column=True, spacing=1000)
  250. # Map frame in metre units
  251. fig.basemap(frame="+n", region=plotregion, projection=f"X{plotsize}c")
  252. # Plot lake boundary in cyan
  253. fig.plot(data=outline_points, region=plotregion, pen="thin,cyan2,-.")
  254. # Plot crossover point locations
  255. pygmt.makecpt(cmap=cmap, series=elev_range, reverse=True)
  256. fig.plot(data=df, style="d0.1c", cmap=True)
  257. # Map frame in kilometre units
  258. with pygmt.config(FONT_ANNOT_PRIMARY=f"{plotsize+2}p", FONT_LABEL=f"{plotsize+2}p"):
  259. fig.basemap(
  260. frame=[
  261. wsne,
  262. 'xa+l"Polar Stereographic X (km)"',
  263. 'ya+l"Polar Stereographic Y (km)"',
  264. ],
  265. region=plotregion / 1000,
  266. projection=f"X{plotsize}c",
  267. )
  268. return fig
  269. def plot_crossovers(
  270. df: pd.DataFrame,
  271. regionname: str,
  272. elev_var: str = "h",
  273. time_var: str = "t",
  274. track_var: str = "track1_track2",
  275. spacing: float = 2.5,
  276. elev_filter: float = 0.2,
  277. outline_points: str or pd.DataFrame = None,
  278. ) -> pygmt.Figure:
  279. """
  280. Plot to show how elevation is changing at many crossover points over time.
  281. Uses PyGMT to produce the figure. The input table should look something like
  282. below (more columns can be present too).
  283. | track1_track2 | h | t |
  284. |------------------|-----|---------------------|
  285. | 0111_pt1x0222pt2 | 111 | 2020-01-01T01:12:34 |
  286. | 0222_pt2x0333pt3 | 110 | 2020-04-01T12:23:45 |
  287. | 0333_pt3x0111pt1 | 101 | 2020-07-01T23:34:56 |
  288. which will produce a plot similar to the following:
  289. ^
  290. | --- * | Ice Stream W |
  291. | \ * \ | y |
  292. |* ---- | -a---a---a---a |
  293. |_______| / | Xover
  294. | x -a-/ -b---b | Elev (m)
  295. | -a---a---a-/ -b-/ |
  296. | -b---b---b---b-/ -c- |
  297. | -c---c---c---c----/ \-c---c |
  298. |_________________________________|
  299. Date
  300. Parameters
  301. ----------
  302. df : pandas.DataFrame
  303. A table containing the ICESat-2 track data from multiple cycles. It
  304. should ideally have columns called 'h', 't', and 'track1_track2'.
  305. regionname : str
  306. A descriptive placename for the data (e.g. Some Ice Stream), to be used
  307. in the figure's main title.
  308. elev_var : str
  309. The elevation column name to use from the table data, plotted on the
  310. vertical y-axis. Default is 'h'.
  311. time_var : str
  312. The time-dimension column name to use from the table data, plotted on
  313. the horizontal x-axis. Default is 't'.
  314. track_var : str
  315. The track column name to use from the table data, containing variables
  316. in the form of track1xtrack2 (note that 'x' is a hardcoded delimiter),
  317. e.g. 0111_pt1x0222pt2. Default is 'track1_track2'.
  318. spacing : str or float
  319. Provide as a 'dy' increment, this is passed on to `pygmt.info` and used
  320. to round up and down the y axis (elev_var) limits for a nicer plot
  321. frame. Default is 2.5.
  322. elev_filter : float
  323. Minimum elevation change required for the crossover point to show up
  324. on the plot. Default is 1.0 (metres).
  325. outline_points : str or pd.DataFrame
  326. A set of nodes making up a polygon to be plotted in a 2D inset map at
  327. one corner of the figure, provided as a pandas.DataFrame table with xyz
  328. columns or a path to an OGR GMT file (necessary for multi-polygons).
  329. Optional.
  330. Returns
  331. -------
  332. fig : pygmt.Figure
  333. A pygmt Figure instance containing the crossover plot which can be
  334. viewed using fig.show() or saved to a file using fig.savefig()
  335. """
  336. fig = pygmt.Figure()
  337. # Setup map frame, title, axis annotations, etc
  338. with pygmt.config(
  339. FONT_ANNOT_PRIMARY="9p",
  340. FORMAT_TIME_PRIMARY_MAP="abbreviated",
  341. FORMAT_DATE_MAP="o",
  342. ):
  343. # Get plot region, spaced out into nice intervals
  344. # Note that passing time columns into pygmt.info doesn't work well yet,
  345. # see https://github.com/GenericMappingTools/pygmt/issues/597
  346. plotregion = np.array(
  347. [
  348. df[time_var].min() - pd.Timedelta(1, unit="W"),
  349. df[time_var].max() + pd.Timedelta(1, unit="W"),
  350. *pygmt.info(table=df[[elev_var]], spacing=spacing)[:2],
  351. ]
  352. )
  353. # pygmt.info(table=df[[time_var, elev_var]], spacing=f"1W/{spacing}", f="0T")
  354. _y_label = "Elevation anomaly" if elev_var == "h_anom" else "Elevation"
  355. fig.basemap(
  356. projection="X12c/12c",
  357. region=plotregion,
  358. frame=[
  359. rf"wSnE",
  360. "pxa1Of1o", # primary time axis, 1 mOnth annotation and minor axis
  361. "sx1Y", # secondary time axis, 1 Year intervals
  362. f'yaf+l"{_y_label} at crossover (m)"',
  363. ],
  364. )
  365. fig.text(
  366. text=regionname, position="TR", justify="TR", offset="-0.2c", font="14p"
  367. )
  368. crossovers = df.groupby(by=track_var)
  369. dh_max = df[elev_var].abs().max()
  370. elev_range = [-dh_max, +dh_max]
  371. pygmt.makecpt(cmap="vik", series=elev_range, reverse=True)
  372. xover: dict = {"x": [], "y": [], "dhdt": []}
  373. for track1_track2, indexes in tqdm.tqdm(crossovers.indices.items()):
  374. df_ = df.loc[indexes].sort_values(by=time_var)
  375. dhdt, _ = np.polyfit(
  376. x=df_[time_var].astype(np.int64), y=df_[elev_var], deg=1
  377. ) * (365.25 * 24 * 60 * 60 * 1_000_000_000)
  378. if abs(dhdt) > elev_filter: # Plot only > 1 metre height change
  379. track1, track2 = track1_track2.split("x")
  380. fig.plot(
  381. x=df_[time_var],
  382. y=df_[elev_var],
  383. zvalue=dhdt,
  384. style="c0.1c",
  385. cmap=True,
  386. pen="thin+z",
  387. )
  388. # Plot line connecting points
  389. fig.plot(
  390. x=df_[time_var],
  391. y=df_[elev_var],
  392. zvalue=dhdt,
  393. pen=f"faint,+z,-",
  394. cmap=True,
  395. )
  396. # Get x, y and color (elev) for inset map
  397. if outline_points:
  398. _x, _y = df_.iloc[0][["x", "y"]]
  399. xover["x"].append(_x)
  400. xover["y"].append(_y)
  401. xover["dhdt"].append(dhdt)
  402. # 2D inset map showing lake outline and crossover point locations
  403. if outline_points:
  404. if df[elev_var].mean() > 0: # uptrend
  405. position, wsne = "TL", "SE"
  406. else: # downtrend
  407. position, wsne = "BL", "NE"
  408. with pygmt.clib.Session() as session:
  409. session.call_module(module="inset", args=f"begin -Dj{position}+w4c -N")
  410. ## Plot insets
  411. fig = _plot_crossover_area(
  412. outline_points=outline_points,
  413. df=pd.DataFrame(data=xover).to_numpy(),
  414. fig=fig,
  415. plotsize=4,
  416. cmap="vik",
  417. elev_range=elev_range,
  418. wsne=wsne,
  419. )
  420. with pygmt.clib.Session() as session:
  421. session.call_module(module="inset", args="end")
  422. return fig
  423. def plot_icesurface(
  424. grid: str or xr.DataArray = None,
  425. grid_region: tuple or np.ndarray = None,
  426. diff_grid: str or xr.DataArray = None,
  427. diff_grid_region: tuple or np.ndarray = None,
  428. track_points: pd.DataFrame = None,
  429. outline_points: str or pd.DataFrame = None,
  430. azimuth: float = 157.5,
  431. elevation: float = 45,
  432. title: str = "",
  433. ) -> pygmt.Figure:
  434. """
  435. Plot to show a 3D perspective of an elevation grid surface on the top, and
  436. the differenced grid on the bottom. Also allows for ovelaying track points
  437. and a polygon outline. This function is custom designed for showcasing
  438. ICESat-2 altimetry data of an active subglacial lake surface changing over
  439. time. The resulting plot will be similar to the right plot below:
  440. ___________ Subglacial Lake X at YYYYMMDD
  441. |__|__|__|__| ^
  442. |__|__|__|__| z |
  443. y |__|__z__|__| | ^~^~~^~ ^
  444. |__|__|__|__| ___________ --> \ ~~^~~~^^~~ \ Elev (m)
  445. |__|__|__|__| |__|__|__|__| \ ~^^~~^~~~ \
  446. x |__|__|__|__| ^ \__ __ __ __ v
  447. y |__|_dz__|__| dz |
  448. |__|__|__|__| | ^~^~~^~ ^
  449. |__|__|__|__| \ ~~^~~~^^~~ \ Diff (m)
  450. x y \ ~^^~~^~~~ \
  451. \__ __ __ __ v
  452. x
  453. Uses `pygmt.grdview` to produce the figure. The main input grid can be a
  454. NetCDF filename or an xarray.DataArray with x, y, z variables, while the
  455. diff_grid must be an xarray.DataArray. Note that there are several
  456. hardcoded defaults like the vertical exaggeration (0.1x) and axis labels.
  457. Parameters
  458. ----------
  459. grid : str or xr.DataArray
  460. The main digital surface elevation model to plot, provided as a file
  461. name or xarray.DataArray grid.
  462. grid_region : tuple or np.ndarray
  463. The bounding cube of the grid given as (xmin, xmax, ymin, ymax, zmin,
  464. zmax).
  465. diff_grid : xr.DataArray
  466. A differenced elevation grid as an xarray.DataArray.
  467. diff_grid_region : tuple or np.ndarray
  468. The bounding cube of the diff_grid given as (xmin, xmax, ymin, ymax,
  469. zmin, zmax).
  470. track_points : pd.DataFrame
  471. Altimetry track points to plot on top of the main grid surface,
  472. provided as a pandas.DataFrame table with xyz columns. Optional.
  473. outline_points : str or pd.DataFrame
  474. A set of nodes making up a polygon to be plotted on top of the main
  475. grid surface, provided as a pandas.DataFrame table with xyz columns or
  476. a path to an OGR GMT file (necessary for multi-polygons). Optional.
  477. azimuth : float
  478. Angle of viewpoint in degrees from 0-360. Default is 157.5 (SSE),
  479. elevation : float
  480. Angle from horizon in degrees from 0-90. Default is 45.
  481. title : str
  482. Main heading text (e.g. "Subglacial Lake X at YYYYMMDD"). Default is ""
  483. (blank).
  484. Returns
  485. -------
  486. fig : pygmt.Figure
  487. A pygmt Figure instance containing the 3D perspective grid plot which
  488. can be viewed using fig.show() or saved to a file using fig.savefig()
  489. """
  490. assert len(grid_region) == 6 # (xmin, xmax, ymin, ymax, zmin, zmax)
  491. fig = pygmt.Figure()
  492. ## Bottom plot
  493. # Normalized ice surface elevation change grid
  494. try:
  495. if diff_grid.min() == diff_grid.max():
  496. # add some tiny random noise to make plot work
  497. np.random.seed(seed=int(elevation))
  498. diff_grid = diff_grid + abs(
  499. np.random.normal(scale=1e-32, size=diff_grid.shape)
  500. )
  501. except AttributeError:
  502. pass
  503. try:
  504. series = diff_grid_region[-2:]
  505. except TypeError:
  506. series = pygmt.grdinfo(grid=diff_grid, nearest_multiple="1+s")[2:-3]
  507. finally:
  508. pygmt.makecpt(cmap="roma", series=series)
  509. fig.grdview(
  510. grid=diff_grid,
  511. projection="X10c",
  512. region=diff_grid_region,
  513. shading=False,
  514. frame=[
  515. f"SWZ", # plot South, West axes, and Z-axis
  516. 'xaf+l"Polar Stereographic X (m)"', # add x-axis annotations and minor ticks
  517. 'yaf+l"Polar Stereographic Y (m)"', # add y-axis annotations and minor ticks
  518. f"zaf", # add z-axis annotations, minor ticks and axis label
  519. ],
  520. cmap=True,
  521. zscale=0.1, # zscaling factor, hardcoded to 0.1x vertical exaggeration
  522. # zsize="5c", # z-axis size, hardcoded to be 5 centimetres
  523. surftype="sim", # surface, image and mesh plot
  524. perspective=[azimuth, elevation], # perspective using azimuth/elevation
  525. # W="c0.05p,black,solid", # draw contours
  526. )
  527. fig.colorbar(
  528. cmap=True,
  529. position="JMR+o1c/0c+w7c/0.5c+n",
  530. frame=[
  531. 'x+l"Elevation Trend"',
  532. "y+lm/yr",
  533. ]
  534. if "?dhdt" in diff_grid
  535. else ['x+l"Elevation Change"', "y+lm"],
  536. perspective=True,
  537. )
  538. ## Top plot
  539. fig.shift_origin(yshift="9c")
  540. # Ice surface elevation grid
  541. pygmt.makecpt(cmap="lapaz", series=grid_region[-2:])
  542. fig.grdview(
  543. grid=grid,
  544. projection="X10c",
  545. region=grid_region,
  546. shading=True,
  547. frame=[
  548. f'SWZ+t"{title}"', # plot South, West axes, and Z-axis
  549. "xf", # add x-axis minor ticks
  550. "yf", # add y-axis minor ticks
  551. f"zaf", # add z-axis annotations, minor ticks and axis label
  552. ],
  553. cmap=True,
  554. zscale=0.1, # zscaling factor, hardcoded to 0.1x vertical exaggeration
  555. # zsize="5c", # z-axis size, hardcoded to be 5 centimetres
  556. surftype="sim", # surface, image and mesh plot
  557. perspective=[azimuth, elevation], # perspective using azimuth/elevation
  558. # W="c0.05p,black,solid", # draw contours
  559. )
  560. fig.colorbar(
  561. cmap=True,
  562. shading=True,
  563. position="JMR+o1c/0c+w7c/0.5c+n",
  564. frame=['x+l"Elevation"', "y+lm"],
  565. perspective=True,
  566. )
  567. # Plot satellite track line points in green
  568. if track_points is not None:
  569. fig.plot3d(
  570. data=track_points,
  571. color="green",
  572. style="c0.02c",
  573. zscale=True,
  574. perspective=True,
  575. )
  576. # Plot lake boundary outline as cyan dashed line
  577. if outline_points is not None:
  578. with pygmt.helpers.GMTTempFile() as tmpfile:
  579. pygmt.grdtrack(
  580. points=outline_points,
  581. grid=grid,
  582. region="/".join(map(str, grid_region[:-2])),
  583. outfile=tmpfile.name,
  584. verbose="e",
  585. )
  586. _df = pd.read_csv(tmpfile.name, sep="\t", names=["x", "y", "z"])
  587. pygmt.grdtrack(
  588. points=outline_points,
  589. grid=grid,
  590. region="/".join(map(str, grid_region[:-2])),
  591. outfile=tmpfile.name,
  592. d=f"o{_df.z.median()}", # fill NaN points with median height
  593. verbose="e",
  594. )
  595. fig.plot3d(
  596. data=tmpfile.name,
  597. region=grid_region,
  598. pen="thicker,cyan2,-.",
  599. zscale=True,
  600. perspective=True,
  601. )
  602. return fig
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...