-
Notifications
You must be signed in to change notification settings - Fork 7
/
cartopy_tools.py
1762 lines (1484 loc) · 59.8 KB
/
cartopy_tools.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
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## Brian Blaylock
## February 3, 2021
## Updated September 18, 2021
"""
=============
Cartopy Tools
=============
General helpers for cartopy plots.
Does projection matter? YES!
(https://www.joaoleitao.com/different-world-map-projections/)
You've looked at maps with distortion that show Greenland the size of
South America. For the same reason, you should show data on appropriate
projection globes. For global plots, consider using Mollweide projection
over Mercator or Robinson. From the website above,
[Mollweide] sacrifices the precision of some of the angles and
shapes, in exchange for a better representation of the planet's
proportions when that is an important consideration.
[Robinson] represented the continents more accurately than the
Mercator Projection, the poles are highly distorted.
This may better help you interpret results. The Winkel Tripel Projection
may also be more appropriate than Robinson, but not yet supported by
Cartopy.
"""
import urllib.request
import warnings
import cartopy.crs as ccrs
import cartopy.feature as feature
import cartopy.io.img_tiles as cimgt
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyproj
import requests
import xarray as xr
import shapely.geometry as sgeom
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition
from cartopy.io import shapereader
from functools import partial
from paint.standard2 import cm_dpt, cm_rh, cm_tmp, cm_wind
import shapely.ops as sops
from toolbox.stock import Path
try:
from metpy.plots import USCOUNTIES
except Exception as e:
# warnings.warn(f"{e} Without metpy, you cannot draw COUNTIES on the map.")
pass
try:
import geopandas
except Exception as e:
# warnings.warn(
# f'{e} Without geopandas, you cannot subset some NaturalEarthFeatures shapefiles, like "Major Highways" from roads.'
# )
pass
pc = ccrs.PlateCarree()
pc._threshold = 0.01 # https://github.com/SciTools/cartopy/issues/8
def _to_180(lon):
"""
Wrap longitude from degrees [0, 360] to degrees [-180, 180].
An alternative method is
lon[lon>180] -= 360
Parameters
----------
lon : array_like
Longitude values
"""
lon = (lon + 180) % 360 - 180
return lon
# Map extent regions.
_extents = dict(
NW=(-180, 0, 0, 90),
SW=(-180, 0, -90, 0),
NE=(0, 180, 0, 90),
SE=(0, 180, -90, 0),
CONUS=(-130, -60, 20, 55),
)
########################################################################
# Methods attached to axes created by `EasyMap`
def _adjust_extent(self, pad="auto", fraction=0.05, verbose=False):
"""
Adjust the extent of an existing cartopy axes.
This is useful to fine-tune the extent of a map after the extent
was automatically made by a cartopy plotting method.
Parameters
----------
pad : float or dict
If float, pad the map the same on all sides. Default is half a degree.
If dict, specify pad on each side.
- 'top' - padding north of center point
- 'bottom'- padding south of center point
- 'left' - padding east of center point
- 'right' - padding west of center point
- 'default' - padding when pad is unspecified
Example: ``pad=dict(top=.5, default=.2)`` is the same as
``pad=dict(top=.5, bottom=.2, left=.2, right=.2)``
Note: Use negative numbers to remove padding.
fraction : float
When pad is 'auto', adjust the sides by a set fraction.
The default 0.05 will give 5% padding on each side.
"""
# Can't shrink the map extent by more than half in each direction, duh.
assert fraction > -0.5, "Fraction must be larger than -0.5."
crs = self.projection
west, east, south, north = self.get_extent(crs=crs)
if pad == "auto":
pad = {}
if isinstance(pad, dict):
xmin, xmax = self.get_xlim()
default_pad = (xmax - xmin) * fraction
pad.setdefault("default", default_pad)
for i in ["top", "bottom", "left", "right"]:
pad.setdefault(i, pad["default"])
else:
pad = dict(top=pad, bottom=pad, left=pad, right=pad)
ymin, ymax = crs.y_limits
north = np.minimum(ymax, north + pad["top"])
south = np.maximum(ymin, south - pad["bottom"])
east = east + pad["right"]
west = west - pad["left"]
self.set_extent([west, east, south, north], crs=crs)
if verbose:
print(f"📐 Adjust Padding for {crs.__class__}: {pad}")
return self.get_extent(crs=crs)
def _center_extent(
self,
lon=None,
lat=None,
city=None,
state=None,
*,
pad="auto",
verbose=False,
):
"""
Change the map extent to be centered on a point and adjust padding.
Parameters
----------
lon, lat : float or None
Latitude and Longitude of the center point **in degrees**.
If None, must give argument for ``city``.
city : str or None
If string, center over city location.
pad : float or dict
Default is 'auto', which defaults to ~5 degree padding on each side.
If float, pad the map the same on all sides (in crs units).
If dict, specify pad on each side (in crs units).
- 'top' - padding north of center point
- 'bottom'- padding south of center point
- 'left' - padding east of center point
- 'right' - padding west of center point
- 'default' - padding when pad is unspecified (default is 5)
Example: ``pad=dict(top=5, default=10)`` is the same as
``pad=dict(top=5, bottom=10, left=10, right=10)``
"""
crs = self.projection
if city is not None:
places = shapereader.natural_earth("10m", "cultural", "populated_places")
df = geopandas.read_file(places)
point = df[df.NAME == city]
assert len(point) > 0, f"🏙 Sorry, the city '{city}' was not found."
lat = point.LATITUDE.item()
lon = point.LONGITUDE.item()
elif state is not None:
state_center = state_polygon(state).centroid
lon = state_center.x
lat = state_center.y
# Convert input lat/lon in degrees to the crs units
lon, lat = crs.transform_point(lon, lat, src_crs=pc)
if pad == "auto":
pad = dict()
if isinstance(pad, dict):
# This default gives 5 degrees padding on each side
# for a PlateCarree projection. Pad is similar for other
# projections but not exactly 5 degrees.
xmin, xmax = crs.x_limits
default_pad = (xmax - xmin) / 72 # Because 360/72 = 5 degrees
pad.setdefault("default", default_pad)
for i in ["top", "bottom", "left", "right"]:
pad.setdefault(i, pad["default"])
else:
pad = dict(top=pad, bottom=pad, left=pad, right=pad)
ymin, ymax = crs.y_limits
north = np.minimum(ymax, lat + pad["top"])
south = np.maximum(ymin, lat - pad["bottom"])
east = lon + pad["right"]
west = lon - pad["left"]
self.set_extent([west, east, south, north], crs=crs)
if verbose:
print(f"📐 Padding from point for {crs.__class__}: {pad}")
return self.get_extent(crs=crs)
def _copy_extent(self, src_ax):
"""
Copy the extent from an axes.
.. note::
Copying extent from different projections might not result in
what you expect.
Parameters
----------
src_ax : cartopy axes
A source cartopy axes to copy extent from onto the existing axes.
Examples
--------
>>> # Copy extent of ax2 to ax1
>>> ax1.copy_extent(ax2)
"""
src_ax = check_cartopy_axes(src_ax)
self.set_extent(src_ax.get_extent(crs=pc), crs=pc)
return self.get_extent(crs=pc)
def _add_cbar(artist, ax=None, labels=None, **cbar_kwargs):
"""
Add a colorbar for an artist to an axis.
Parameters
----------
artist : object from pcolormesh or with a cmap
An pyplot object with a cmap.
ax : pyplot.axesis the axes
An axes. If none is provided, one will be created.
labels : list
A list of tick labels for the colorbar.
"""
if ax is None:
ax = plt.gca()
cbar_kwargs.setdefault("orientation", "horizontal")
cbar_kwargs.setdefault("pad", 0.02)
cbar_kwargs.setdefault("fraction", 0.045)
c = plt.colorbar(artist, ax=ax, **cbar_kwargs)
if labels is not None:
assert (
"ticks" in cbar_kwargs
), "You gave me `labels`...Please supply the `ticks` kwarg, too."
if cbar_kwargs["orientation"] == "horizontal":
c.ax.set_xticklabels(labels, rotation=90)
else:
c.ax.set_yticklabels(labels)
return c
########################################################################
# Main Functions
def check_cartopy_axes(ax=None, crs=pc, *, fignum=None, verbose=False):
"""
Check if an axes is a cartopy axes, else create a new cartopy axes.
Parameters
----------
ax : {None, cartopy.mpl.geoaxes.GeoAxesSubplot}
If None and plt.gca() is a cartopy axes, then use current axes.
Else, create a new cartopy axes with specified crs.
crs : cartopy.crs
If the axes being checked is not a cartopy axes, then create one
with this coordinate reference system (crs, aka "projection").
Default is ccrs.PlateCarree()
fignum : int
If given, create a new figure and supblot for the given crs.
(This might be handy in a loop when you want to create maps on
several figures instead of plotting on the same figure.)
"""
if isinstance(fignum, int):
plt.figure(fignum)
ax = plt.subplot(1, 1, 1, projection=crs)
return ax
# A cartopy axes should be of type `cartopy.mpl.geoaxes.GeoAxesSubplot`
# One way to check that is to see if ax has the 'coastlines' attribute.
if ax is None:
if hasattr(plt.gca(), "coastlines"):
if verbose:
print("🌎 Using the current cartopy axes.")
return plt.gca()
else:
if verbose:
print(
f"🌎 The current axes is not a cartopy axes. Will create a new cartopy axes with crs={crs.__class__}."
)
# Close the axes we just opened in our test
plt.close()
# Create a new cartopy axes
return plt.axes(projection=crs)
else:
if hasattr(ax, "coastlines"):
if verbose:
print("🌎 Thanks! It appears the axes you provided is a cartopy axes.")
return ax
else:
raise TypeError("🌎 Sorry. The `ax` you gave me is not a cartopy axes.")
def get_ETOPO1(top="ice", coarsen=None, thin=None):
"""
Return the ETOPO1 elevation and bathymetry DataArray.
The ETOPO1 dataset is huge (446 MB). This function saves coarsened
versions of the data for faster loading.
Download the data from http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NGDC
An alternatvie source is https://ngdc.noaa.gov/mgg/global/, but the
Dataset may have a different structure.
Parameters
----------
top : {'bedrock', 'ice'}
There are two types of ETOPO1 files, one that is the top of the
ice layers, and another that is the top of the bedrock. This
is necessary for Greenland and Antarctic ice sheets. I'm guessing
that 99% of the time you will want the top of the ice sheets.
thin : int
Thin the Dataset by getting every nth element
coarsen : int
Coarsen the Dataset by taking the mean of the nxn box.
"""
def _reporthook(a, b, c):
"""
Print download progress in megabytes.
Parameters
----------
a : Chunk number
b : Maximum chunk size
c : Total size of the download
"""
chunk_progress = a * b / c * 100
total_size_MB = c / 1000000.0
print(
f"\r🚛💨 Download ETOPO1 {top} Progress: {chunk_progress:.2f}% of {total_size_MB:.1f} MB\r",
end="",
)
if coarsen == 1:
coarsen = None
if thin == 1:
thin = None
assert not all([coarsen, thin]), "Both `coarsen` and `thin` cannot be None."
# If the ETOPO1 data does not exists, then download it.
# The coarsen method is slow, so save a copy to load.
# The thin method is fast, so don't worry about saving a copy.
src = f"http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NGDC/.ETOPO1/.z_{top}/data.nc"
dst = Path(f"$HOME/.local/share/ETOPO1/ETOPO1_{top}.nc").expand()
dst_coarsen = Path(
f"$HOME/.local/share/ETOPO1/ETOPO1_{top}_coarsen-{coarsen}.nc"
).expand()
if not dst.exists():
# Download the full ETOPO1 dataset
if not dst.parent.exists():
dst.parent.mkdir(parents=True)
urllib.request.urlretrieve(src, dst, _reporthook)
print(f"{' ':70}", end="")
if coarsen:
if dst_coarsen.exists():
ds = xr.open_dataset(dst_coarsen)
else:
ds = xr.open_dataset(dst)
ds = ds.coarsen({"lon": coarsen, "lat": coarsen}, boundary="pad").mean()
ds.to_netcdf(dst_coarsen)
else:
ds = xr.open_dataset(dst)
if thin:
ds = ds.thin(thin)
return ds[f"z_{top}"]
def inset_global_map(ax, x=0.95, y=0.95, size=0.3, dark=True, facecolor="#f88d0083"):
"""Add an inset map showing the location of the main map on the globe.
This was pieced together from these resources
- https://predictablysunny.com/posts/inset_map_cartopy/
- https://scitools.org.uk/cartopy/docs/latest/gallery/lines_and_polygons/effects_of_the_ellipse.html#sphx-glr-gallery-lines-and-polygons-effects-of-the-ellipse-py
- https://stackoverflow.com/a/53712048/2383070
Parameters
----------
ax : a cartopy axes
A cartopy axes with the extent already set (not global).
"""
# ======================
# Find the extent center
extent = ax.get_extent(crs=pc)
center_lon = (extent[0] + extent[1]) / 2
center_lat = (extent[2] + extent[3]) / 2
# ====================
# Create the Inset Map
# Location and size of inset on axis
inset_x = x
inset_y = y
inset_size = size
# Create and position inset
ortho = ccrs.Orthographic(central_latitude=center_lat, central_longitude=center_lon)
ax_inset = plt.axes([0, 0, 1, 1], projection=ortho)
ax_inset.set_global()
ip = InsetPosition(
ax, [inset_x - inset_size / 2, inset_y - inset_size / 2, inset_size, inset_size]
)
ax_inset.set_axes_locator(ip)
# ===================
# Inset Map Cosmetics
EasyMap(ax=ax_inset, dark=dark, linewidth=0).STATES().LAND().OCEAN()
ax_inset.gridlines(
xlocs=range(-180, 180, 10),
ylocs=range(-90, 91, 10),
lw=0.1,
alpha=0.2,
)
# =========================
# Add Bounding Box to Inset
# Create Boundary box: need to increase the boundary of box Polygon coords
crs_extent = ax.get_extent(crs=ax.projection)
ring = sgeom.box(
crs_extent[0], crs_extent[2], crs_extent[1], crs_extent[3]
).exterior
# Set the number of points along a side
n_points = 200
# Create a new LinearRing with additional points
new_ring_coords = []
for i in range(len(ring.coords) - 1):
start = ring.coords[i]
end = ring.coords[i + 1]
line = sgeom.LineString([start, end])
new_points = [
line.interpolate(i) for i in np.linspace(1, line.length, n_points)
]
new_ring_coords += [start] + new_points + [end]
new_ring = sgeom.LinearRing(new_ring_coords)
# Add bounding box to map
ax_inset.add_geometries(
[new_ring],
crs=ax.projection,
facecolor=facecolor,
)
return ax_inset
class EasyMap:
"""
Build a matplotlib/cartopy axes with common map elements.
This class does about 95% of my Cartopy needs.
Feature elements from https://www.naturalearthdata.com/features/
TODO: Rename to CommonFeatures or EasyMap
"""
def __init__(
self,
scale="110m",
ax=None,
crs=pc,
*,
figsize=None,
fignum=None,
dpi=None,
dark=False,
verbose=False,
add_coastlines=True,
facecolor=None,
coastlines_kw={},
**kwargs,
):
"""
Initialize a Cartopy axes
Add coastlines with this method. Use other methods to add
other common features to the Cartopy axes.
.. tip:: ``ax=None`` is a great way to initialize a new Cartopy axes.
Methods
-------
.adjust_extent
.center_extent
.copy_extent
Parameters
----------
scale : {'10m', '50m' 110m'}
The cartopy feature's level of detail.
.. note:: The ``'10m'`` scale for OCEAN and LAND takes a *long* time.
ax : plot axes
The axis to add the feature to.
If None, it will create a new cartopy axes with ``crs``.
crs : cartopy.crs
Coordinate reference system (aka "projection") to create new map
if no cartopy axes is given. Default is ccrs.PlateCarree.
dark : bool
If True, use alternative "dark theme" colors for land and water.
.. figure:: _static/BB_maps/common_features-1.png
.. figure:: _static/BB_maps/common_features-2.png
add_coastlines : bool
For convince, the coastlines are added to the axes by default.
This can be turned off and instead controlled with the COASTLINES
method.
coastlines_kw : dict
kwargs for the default COASTLINES method.
figsize : tuple or float
Set the figure size.
If single number given, then will make a square figure.
fignum : int
If given, create a new figure and supblot for the given crs.
(This might be handy in a loop when you want to create maps on
several figures instead of plotting on the same figure.)
dpi : int
Set the figure dpi
Examples
--------
https://github.com/blaylockbk/Carpenter_Workshop/blob/main/notebooks/demo_cartopy_tools.ipynb
>>> feat = EasyMap()
>>> feat.OCEAN().STATES()
>>> ax = feat.ax
Alternatively,
>>> ax = EasyMap().ax
>>> feat = ax.EasyMap
>>> feat.OCEAN().STATES()
"""
self.scale = scale
self.ax = ax
self.crs = crs
self.figsize = figsize
self.fignum = fignum
self.dpi = dpi
self.dark = dark
self.verbose = verbose
self.kwargs = kwargs
self.ax = check_cartopy_axes(
ax=self.ax, crs=self.crs, fignum=self.fignum, verbose=self.verbose
)
# In a round-about way, you can get this EasyMap object from the axes
# >>> ax = EasyMap().ax
# >>> ax.EasyMap.STATES()
self.ax.EasyMap = self
self.kwargs.setdefault("linewidth", 0.75)
# NOTE: I don't use the 'setdefault' method here because it doesn't
# work as expect when switching between dark and normal themes.
# The defaults would be set the first time the function is called,
# but the next time it is called and `dark=True` the defaults do not
# reset. I don't know why this is the behavior.
if self.dark:
self.land = "#060613" # dark (default)
self.land1 = "#3f3f3f" # lighter (alternative)
self.water = "#0f2b38"
# https://github.com/SciTools/cartopy/issues/880
self.ax.set_facecolor(self.land) # requires cartopy >= 0.18
self.kwargs = {**{"edgecolor": ".5"}, **self.kwargs}
else:
self.land = "#efefdb" # tan (default)
self.land1 = "#dbdbdb" # grey (alternative)
self.water = "#97b6e1"
self.kwargs = {**{"edgecolor": ".15"}, **self.kwargs}
if facecolor:
# Instead of applying both LAND and OCEAN,
# it may be faster to just set the facecolor of land
# and then only apply the OCEAN method.
if facecolor.lower() == "land":
self.ax.set_facecolor(self.land)
elif facecolor.lower() == "land1":
self.ax.set_facecolor(self.land1)
elif facecolor.lower() == "water":
self.ax.set_facecolor(self.water)
else:
self.ax.set_facecolor(facecolor)
if add_coastlines:
# Default map will automatically add COASTLINES
self.COASTLINES(**coastlines_kw)
if figsize is not None:
if hasattr(figsize, "__len__"):
plt.gcf().set_figwidth(self.figsize[0])
plt.gcf().set_figheight(self.figsize[1])
else:
plt.gcf().set_figwidth(self.figsize)
plt.gcf().set_figheight(self.figsize)
if dpi is not None:
plt.gcf().set_dpi(self.dpi)
# Add my custom methods
self.ax.__class__.adjust_extent = _adjust_extent
self.ax.__class__.center_extent = _center_extent
self.ax.__class__.copy_extent = _copy_extent
# Feature Elements
def COASTLINES(self, **kwargs):
kwargs.setdefault("zorder", 100)
kwargs.setdefault("facecolor", "none")
kwargs = {**self.kwargs, **kwargs}
self.ax.add_feature(feature.COASTLINE.with_scale(self.scale), **kwargs)
if self.verbose == "debug":
print("🐛 COASTLINES:", kwargs)
return self
def BORDERS(self, **kwargs):
"""Borders between countries. *Excludes coastlines*"""
kwargs.setdefault("linewidth", 0.5)
kwargs = {**self.kwargs, **kwargs}
self.ax.add_feature(feature.BORDERS.with_scale(self.scale), **kwargs)
if self.verbose == "debug":
print("🐛 BORDERS:", kwargs)
return self
def STATES(self, **kwargs):
"""State and Province borders. *Includes coastlines*
Note: If scale="110m", only the US States are drawn.
If scale="50m", then more country states/provinces are drawn.
If scale="10m", then even *more* countries drawn.
"""
kwargs.setdefault("alpha", 0.15)
kwargs = {**self.kwargs, **kwargs}
self.ax.add_feature(feature.STATES.with_scale(self.scale), **kwargs)
if self.verbose == "debug":
print("🐛 STATES:", kwargs)
return self
def STATES2(self, **kwargs):
"""States and Provinces (US, Canada, Australia, Brazil, China, Inda, etc.)
Alternative source for data than provided by STATES.
"""
kwargs.setdefault("alpha", 0.15)
kwargs = {**self.kwargs, **kwargs}
states_provinces = feature.NaturalEarthFeature(
category="cultural",
name="admin_1_states_provinces_lines",
scale="50m",
facecolor="none",
)
self.ax.add_feature(states_provinces, **kwargs)
if self.verbose == "debug":
print("🐛 STATES2:", kwargs)
return self
def COUNTIES(self, counties_scale="20m", **kwargs):
"""US counties. *Includes coastslines*"""
_counties_scale = {"20m", "5m", "500k"}
assert (
counties_scale in _counties_scale
), f"counties_scale must be {_counties_scale}"
kwargs.setdefault("linewidth", 0.33)
kwargs.setdefault("alpha", 0.15)
kwargs = {**self.kwargs, **kwargs}
self.ax.add_feature(USCOUNTIES.with_scale(counties_scale), **kwargs)
if self.verbose == "debug":
print("🐛 COUNTIES:", kwargs)
return self
def OCEAN(self, **kwargs):
"""Color-filled ocean area"""
kwargs.setdefault("edgecolor", "none")
kwargs = {**self.kwargs, **kwargs}
if self.dark:
kwargs = {**{"facecolor": self.water}, **kwargs}
self.ax.add_feature(feature.OCEAN.with_scale(self.scale), **kwargs)
if self.verbose == "debug":
print("🐛 OCEAN:", kwargs)
return self
def LAND(self, **kwargs):
"""Color-filled land area"""
kwargs.setdefault("edgecolor", "none")
kwargs.setdefault("linewidth", 0)
kwargs = {**self.kwargs, **kwargs}
if self.dark:
kwargs = {**{"facecolor": self.land}, **kwargs}
self.ax.add_feature(feature.LAND.with_scale(self.scale), **kwargs)
if self.verbose == "debug":
print("🐛 LAND:", kwargs)
return self
def RIVERS(self, **kwargs):
"""Rivers"""
kwargs.setdefault("linewidth", 0.3)
kwargs = {**self.kwargs, **kwargs}
if self.dark:
kwargs = {**{"color": self.water}, **kwargs}
else:
kwargs = {**{"color": self.water}, **kwargs}
self.ax.add_feature(feature.RIVERS.with_scale(self.scale), **kwargs)
if self.verbose == "debug":
print("🐛 RIVERS:", kwargs)
return self
def LAKES(self, **kwargs):
"""Color-filled lake area"""
kwargs.setdefault("linewidth", 0)
kwargs = {**self.kwargs, **kwargs}
if self.dark:
kwargs = {**{"facecolor": self.water}, **kwargs}
kwargs = {**{"edgecolor": self.water}, **kwargs}
else:
kwargs = {**{"facecolor": feature.COLORS["water"]}, **kwargs}
kwargs = {**{"edgecolor": feature.COLORS["water"]}, **kwargs}
self.ax.add_feature(feature.LAKES.with_scale(self.scale), **kwargs)
if self.verbose == "debug":
print("🐛 LAKES:", kwargs)
return self
def TERRAIN(
self,
coarsen=30,
*,
top="ice",
kind="pcolormesh",
extent=None,
**kwargs,
):
"""
Plot terrain data from ETOPO1 dataset.
Parameters
----------
coarsen : int
ETOPO1 data is a 1-minute arc dataset. This is huge.
For global plots, you don't need this resolution, and can
be happy with a 30-minute arc resolution (default).
top : {"ice", "bedrock"}
Top of the elevation model. "ice" is top of ice sheets in
Greenland and Antarctica and "bedrock" is elevation of
of ground under the ice.
kind : {"contourf", "pcolormesh"}
Plot data as a contour plot or pcolormesh
extent :
Trim the huge dataset to a specific region. (Variable cases).
- by hemisphere {"NE", "SE", "NW", "SW"}
- by region {"CONUS"}
- by extent (len==4 tuple/list), e.g. `[-130, -100, 20, 50]`
- by xarray.Dataset (must have coordinates 'lat' and 'lon')
TODO: Currently does not allow domains that cross -180 lon.
"""
da = get_ETOPO1(top=top, coarsen=coarsen)
if extent:
if isinstance(extent, (list, tuple)):
assert (
len(extent) == 4
), "extent tuple must be len 4 (minLon, maxLon, minLat, maxLat)"
elif isinstance(extent, str):
assert (
extent in _extents
), f"extent string must be one of {_extents.keys()}"
extent = _extents[extent]
elif hasattr(extent, "coords"):
# Get extent from lat/lon bounds in xarray DataSet
extent = extent.rename({"latitude": "lat", "longitude": "lon"})
extent["lon"] = _to_180(extent["lon"])
extent = (
extent.lon.min().item(),
extent.lon.max().item(),
extent.lat.min().item(),
extent.lat.max().item(),
)
da = da.where(
(da.lon >= extent[0])
& (da.lon <= extent[1])
& (da.lat >= extent[2])
& (da.lat <= extent[3])
)
# Get "land" points (elevation is 0 and above, crude estimation)
da = da.where(da >= 0)
kwargs.setdefault("zorder", 0)
kwargs.setdefault("cmap", "YlOrBr")
kwargs.setdefault("levels", range(0, 8000, 500))
kwargs.setdefault("vmin", 0)
kwargs.setdefault("vmax", 8000)
if kind == "contourf":
_ = kwargs.pop("vmax")
_ = kwargs.pop("vmin")
self.ax.contourf(da.lon, da.lat, da, transform=pc, **kwargs)
elif kind == "pcolormesh":
_ = kwargs.pop("levels")
self.ax.pcolormesh(da.lon, da.lat, da, transform=pc, **kwargs)
return self
def BATHYMETRY(
self,
coarsen=30,
*,
top="ice",
kind="pcolormesh",
extent=None,
**kwargs,
):
"""
Plot bathymetry data from ETOPO1 dataset.
Parameters
----------
coarsen : int
ETOPO1 data is a 1-minute arc dataset. This is huge.
For global plots, you don't need this resolution, and can
be happy with a 30-minute arc resolution (default).
top : {"ice", "bedrock"}
Top of the elevation model. "ice" is top of ice sheets in
Greenland and Antarctica and "bedrock" is elevation of
of ground under the ice.
kind : {"contourf", "pcolormesh"}
Plot data as a contour plot or pcolormesh
extent :
Trim the huge dataset to a specific region. (Variable cases).
- by hemisphere {"NE", "SE", "NW", "SW"}
- by region {"CONUS"}
- by extent (len==4 tuple/list), e.g. `[-130, -100, 20, 50]`
- by xarray.Dataset (must have coordinates 'lat' and 'lon')
TODO: Currently does not allow domains that cross -180 lon.
"""
da = get_ETOPO1(top=top, coarsen=coarsen)
if extent:
if isinstance(extent, (list, tuple)):
assert (
len(extent) == 4
), "extent tuple must be len 4 (minLon, maxLon, minLat, maxLat)"
elif isinstance(extent, str):
assert (
extent in _extents
), f"extent string must be one of {_extents.keys()}"
extent = _extents[extent]
elif hasattr(extent, "coords"):
# Get extent from lat/lon bounds in xarray DataSet
extent = extent.rename({"latitude": "lat", "longitude": "lon"})
extent["lon"] = _to_180(extent["lon"])
extent = (
extent.lon.min().item(),
extent.lon.max().item(),
extent.lat.min().item(),
extent.lat.max().item(),
)
da = da.where(
(da.lon >= extent[0])
& (da.lon <= extent[1])
& (da.lat >= extent[2])
& (da.lat <= extent[3])
)
# Get "water" points (elevation is 0 and above, crude estimation)
da = da.where(da <= 0)
kwargs.setdefault("zorder", 0)
kwargs.setdefault("cmap", "Blues_r")
kwargs.setdefault("levels", range(-10000, 1, 500))
kwargs.setdefault("vmax", 0)
kwargs.setdefault("vmin", -10000)
if kind == "contourf":
_ = kwargs.pop("vmax")
_ = kwargs.pop("vmin")
self.ax.contourf(da.lon, da.lat, da, transform=pc, **kwargs)
elif kind == "pcolormesh":
_ = kwargs.pop("levels")
self.ax.pcolormesh(da.lon, da.lat, da, transform=pc, **kwargs)
return self
def PLAYAS(self, **kwargs):
"""Color-filled playa area"""
kwargs.setdefault("linewidth", 0)
kwargs = {**self.kwargs, **kwargs}
if self.dark:
kwargs = {**{"facecolor": "#4D311A73"}, **kwargs}
kwargs = {**{"edgecolor": "none"}, **kwargs}
else:
kwargs = {**{"facecolor": "#FDA65473"}, **kwargs}
kwargs = {**{"edgecolor": "none"}, **kwargs}
playa = feature.NaturalEarthFeature("physical", "playas", "10m")
self.ax.add_feature(playa, **kwargs)
if self.verbose == "debug":
print("🐛 PLAYAS:", kwargs)
return self
def TIMEZONE(self, **kwargs):
"""Timezone boundaries"""
kwargs.setdefault("linewidth", 0.2)
kwargs.setdefault("facecolor", "none")
kwargs.setdefault("linestyle", ":")
kwargs = {**self.kwargs, **kwargs}
tz = feature.NaturalEarthFeature("cultural", "time_zones", "10m")
self.ax.add_feature(tz, **kwargs)
if self.verbose == "debug":
print("🐛 TIMEZONE:", kwargs)
return self
def ROADS(self, road_types=None, **kwargs):
"""
Major roads
Parameters
----------
road_types : None, str, list
Filter the types of roads you want. The road type may be a single
string or a list of road types.
e.g. ['Major Highway', 'Secondary Highway']
Of course, the shapefile has many other road classifiers for each
road, like "level" (Federal, State, Interstate), road "name",