-
Notifications
You must be signed in to change notification settings - Fork 22
/
eomaps.py
4130 lines (3359 loc) · 144 KB
/
eomaps.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
# Copyright EOmaps Contributors
#
# This file is part of EOmaps and is released under the BSD 3-clause license.
# See LICENSE in the root of the repository for full licensing details.
"""General definition of Maps objects."""
import logging
_log = logging.getLogger(__name__)
from contextlib import ExitStack
from functools import lru_cache, wraps
from itertools import repeat, chain
from pathlib import Path
from types import SimpleNamespace
from textwrap import fill
import copy
import importlib.metadata
import weakref
import numpy as np
from pyproj import CRS
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.path import Path as mpath
from cartopy import crs as ccrs
from ._maps_base import MapsBase
from .helpers import (
pairwise,
cmap_alpha,
progressbar,
SearchTree,
_TransformedBoundsLocator,
register_modules,
_key_release_event,
_add_to_docstring,
)
from .shapes import Shapes
from .colorbar import ColorBar
from ._containers import DataSpecs, ClassifySpecs
from .ne_features import NaturalEarthFeatures
from .cb_container import CallbackContainer, GeoDataFramePicker
from .scalebar import ScaleBar
from .compass import Compass
from .reader import read_file, from_file, new_layer_from_file
from .grid import GridFactory
from .utilities import Utilities
from .draw import ShapeDrawer
from .annotation_editor import AnnotationEditor
from ._data_manager import DataManager
try:
from ._webmap import refetch_wms_on_size_change, _cx_refetch_wms_on_size_change
from .webmap_containers import WebMapContainer
except ImportError as ex:
_log.error(f"EOmaps: Unable to import dependencies required for WebMaps: {ex}")
refetch_wms_on_size_change = None
_cx_refetch_wms_on_size_change = None
WebMapContainer = None
__version__ = importlib.metadata.version("eomaps")
# hardcoded list of available mapclassify-classifiers
# (to avoid importing it on startup)
_CLASSIFIERS = (
"BoxPlot",
"EqualInterval",
"FisherJenks",
"FisherJenksSampled",
"HeadTailBreaks",
"JenksCaspall",
"JenksCaspallForced",
"JenksCaspallSampled",
"MaxP",
"MaximumBreaks",
"NaturalBreaks",
"Quantiles",
"Percentiles",
"StdMean",
"UserDefined",
)
class Maps(MapsBase):
"""
The base-class for generating plots with EOmaps.
The first Maps object that is initialized will create a new matplotlib `Figure`
and a cartopy `GeoAxes` for a map.
You can then create additional `Maps` objects on the same figure with the following
methods:
See Also
--------
Maps.new_layer : Create a new layer for the map.
Maps.new_map : Add a new map to the figure.
Maps.new_inset_map : Add a new inset-map to the figure.
:py:class:`~eomaps.mapsgrid.MapsGrid` : Initialize a grid of Maps objects
Parameters
----------
crs : int or a cartopy-projection, optional
The projection of the map.
If int, it is identified as an epsg-code
Otherwise you can specify any projection supported by `cartopy.crs`
A list for easy-accses is available as `Maps.CRS`
The default is 4326.
layer : str, optional
The name of the plot-layer assigned to this Maps-object.
The default is "base".
Other Parameters
----------------
f : matplotlib.Figure, optional
Explicitly specify the matplotlib figure instance to use.
(ONLY useful if you want to add a map to an already existing figure!)
- If None, a new figure will be created (accessible via m.f)
- Connected maps-objects will always share the same figure! You do
NOT need to specify it (just provide the parent and you're fine)!
The default is None
ax : int, list, tuple, matplotlib.Axes, matplotlib.gridspec.SubplotSpec or None
Explicitly specify the position of the axes or use already existing axes.
Possible values are:
- None:
Initialize a new axes at the center of the figure (the default)
- A tuple of 4 floats (*left*, *bottom*, *width*, *height*)
The absolute position of the axis in relative figure-coordinates
(e.g. in the range [0 , 1])
NOTE: since the axis-size is dependent on the plot-extent, the size of
the map will be adjusted to fit in the provided bounding-box.
- A tuple of 3 integers (*nrows*, *ncols*, *index*)
The map will be positioned at the *index* position of a grid
with *nrows* rows and *ncols* columns. *index* starts at 1 in the
upper left corner and increases to the right. *index* can also be
a two-tuple specifying the (*first*, *last*) indices (1-based, and
including *last*) of the subplot, e.g., ``ax = (3, 1, (1, 2))``
makes a map that spans the upper 2/3 of the figure.
- A 3-digit integer
Same as using a tuple of three single-digit integers.
(e.g. 111 is the same as (1, 1, 1) )
- `matplotilb.gridspec.SubplotSpec`:
Use the SubplotSpec for initializing the axes.
- `matplotilb.Axes`:
Directly use the provided figure and axes instances for plotting.
NOTE: The axes MUST be a geo-axes with `m.crs_plot` projection!
preferred_wms_service : str, optional
Set the preferred way for accessing WebMap services if both WMS and WMTS
capabilities are possible.
The default is "wms"
kwargs :
additional kwargs are passed to `matplotlib.pyplot.figure()`
- e.g. figsize=(10,5)
Examples
--------
Create a new Maps object and initialize a figure and axes for a map.
>>> from eomaps import Maps
>>> m = Maps()
>>> # add basic background features to the map
>>> m.add_feature.preset("coastline", "ocean", "land")
>>> # create a new layer and add more features
>>> m1 = m.new_layer("layer 1")
>>> m1.add_feature.physical.coastline(fc="none", ec="b", lw=2, scale=50)
>>> m1.add_feature.cultural.admin_0_countries(fc=(.2,.1,.4,.2), ec="b", lw=1, scale=50)
>>> # overlay a part of the new layer in a circle if you click on the map
>>> m.cb.click.attach.peek_layer(m1.layer, how=0.4, shape="round")
Use Maps-objects as context-manager to close the map and free memory
once the map is exported.
>>> from eomaps import Maps
>>> with Maps() as m:
>>> m.add_feature.preset.coastline()
>>> m.savefig(...)
Note
----
You can access possible crs via the `CRS` accessor (alias of `cartopy.crs`):
>>> m = Maps(crs=Maps.CRS.Orthographic())
"""
__version__ = __version__
from_file = from_file
read_file = read_file
CRS = ccrs
# the keyboard shortcut to activate the companion-widget
_companion_widget_key = "w"
# max. number of layers to show all layers as tabs in the widget
# (otherwise only recently active layers are shown as tabs)
_companion_widget_n_layer_tabs = 50
CLASSIFIERS = SimpleNamespace(**dict(zip(_CLASSIFIERS, _CLASSIFIERS)))
"Accessor for available classification schemes."
# arguments passed to m.savefig when using "ctrl+c" to export figure to clipboard
_clipboard_kwargs = dict()
# to make namespace accessible for sphinx
set_shape = Shapes
draw = ShapeDrawer
add_feature = NaturalEarthFeatures
util = Utilities
cb = CallbackContainer
classify_specs = ClassifySpecs
data_specs = DataSpecs
if WebMapContainer is not None:
add_wms = WebMapContainer
def __init__(
self,
crs=None,
layer="base",
f=None,
ax=None,
preferred_wms_service="wms",
**kwargs,
):
super().__init__(
crs=crs,
layer=layer,
f=f,
ax=ax,
**kwargs,
)
self._log_on_event_messages = dict()
self._log_on_event_cids = dict()
try:
from .qtcompanion.signal_container import _SignalContainer
# initialize the signal container (MUST be done before init of the widget!)
self._signal_container = _SignalContainer()
except Exception:
_log.debug("SignalContainer could not be initialized", exc_info=True)
self._signal_container = None
self._inherit_classification = None
self._util = None
self._colorbars = []
self._coll = None # slot for the collection created by m.plot_map()
self._companion_widget = None # slot for the pyqt widget
self._cid_keypress = None # callback id for PyQt5 keypress callbacks
# attach a callback to show/hide the companion-widget with the "w" key
if self.parent._cid_keypress is None:
# NOTE the companion-widget is ONLY attached to the parent map
# since it will identify the clicked map automatically! The
# widget will only be initialized on Maps-objects that create
# NEW axes. This is required to make sure that any additional
# Maps-object on the same axes will then always use the
# same widget. (otherwise each layer would get its own widget)
self.parent._cid_keypress = self.f.canvas.mpl_connect(
"key_press_event", self.parent._on_keypress
)
# a list to remember newly registered colormaps
self._registered_cmaps = []
# a list of actions that are executed whenever the widget is shown
self._on_show_companion_widget = []
# preferred way of accessing WMS services (used in the WMS container)
assert preferred_wms_service in [
"wms",
"wmts",
], "preferred_wms_service must be either 'wms' or 'wmts' !"
self._preferred_wms_service = preferred_wms_service
# default classify specs
self.classify_specs = ClassifySpecs(weakref.proxy(self))
self.data_specs = DataSpecs(
weakref.proxy(self),
x=None,
y=None,
crs=4326,
)
# initialize the data-manager
self._data_manager = DataManager(self._proxy(self))
self._data_plotted = False
self._set_extent_on_plot = True
self.cb = self.cb(weakref.proxy(self)) # accessor for the callbacks
# initialize the callbacks
self.cb._init_cbs()
if WebMapContainer is not None:
self.add_wms = self.add_wms(weakref.proxy(self))
self._new_layer_from_file = new_layer_from_file(weakref.proxy(self))
self.set_shape = self.set_shape(weakref.proxy(self))
self._shape = None
# the dpi used for shade shapes
self._shade_dpi = None
# the radius is estimated when plot_map is called
self._estimated_radius = None
# a set to hold references to the compass objects
self._compass = set()
if not hasattr(self.parent, "_wms_legend"):
self.parent._wms_legend = dict()
if not hasattr(self.parent, "_execute_callbacks"):
self.parent._execute_callbacks = True
# evaluate and cache crs boundary bounds (for extent clipping)
self._crs_boundary_bounds = self.crs_plot.boundary.bounds
# a factory to create gridlines
if self.parent == self:
self._grid = GridFactory(self.parent)
if Maps._always_on_top:
self._set_always_on_top(True)
self.add_feature = self.add_feature(weakref.proxy(self))
self.draw = self.draw(weakref.proxy(self))
if self.parent == self:
self.util = Utilities(self)
else:
self.util = self.parent.util
@property
def coll(self):
"""The collection representing the dataset plotted by m.plot_map()."""
return self._coll
@property
def _shape_assigned(self):
"""Return True if the shape is explicitly assigned and False otherwise"""
# the shape is considered assigned if an explicit shape is set
# or if the data has been plotted with the default shape
q = self._shape is None or (
getattr(self._shape, "_is_default", False) and not self._data_plotted
)
return not q
@property
def shape(self):
"""
The shape that is used to represent the dataset if `m.plot_map()` is called.
By default "ellipses" is used for datasets < 500k datapoints and for plots
where no explicit data is assigned, and otherwise "shade_raster" is used
for 2D datasets and "shade_points" is used for unstructured datasets.
"""
if not self._shape_assigned:
self._set_default_shape()
self._shape._is_default = True
return self._shape
@property
def colorbar(self):
"""
Get the **most recently added** colorbar of this Maps-object.
Returns
-------
ColorBar
EOmaps colorbar object.
"""
if len(self._colorbars) > 0:
return self._colorbars[-1]
@property
def data(self):
"""The data assigned to this Maps-object."""
return self.data_specs.data
@data.setter
def data(self, val):
# for downward-compatibility
self.data_specs.data = val
@lru_cache()
def get_crs(self, crs="plot"):
"""
Get the pyproj CRS instance of a given crs specification.
Parameters
----------
crs : "in", "out" or a crs definition
the crs to return
- if "in" : the crs defined in m.data_specs.crs
- if "out" or "plot" : the crs used for plotting
Returns
-------
crs : pyproj.CRS
the pyproj CRS instance
"""
# check for strings first to avoid expensive equality checking for CRS objects!
if isinstance(crs, str):
if crs == "in":
crs = self.data_specs.crs
elif crs == "out" or crs == "plot":
crs = self.crs_plot
crs = CRS.from_user_input(crs)
return crs
@property
def _edit_annotations(self):
if getattr(self.parent, "_edit_annotations_parent", None) is None:
self.parent._edit_annotations_parent = AnnotationEditor(self.parent)
return self.parent._edit_annotations_parent
@wraps(AnnotationEditor.__call__)
def edit_annotations(self, b=True, **kwargs):
self._edit_annotations(b, **kwargs)
@property
@wraps(new_layer_from_file)
def new_layer_from_file(self):
"""Create a new layer from a file."""
return self._new_layer_from_file
def new_map(
self,
ax=None,
keep_on_top=False,
inherit_data=False,
inherit_classification=False,
inherit_shape=False,
**kwargs,
):
"""
Create a new map that shares the figure with this Maps-object.
Note
----
Using this function, for example:
>>> m = Maps(ax=211)
>>> m2 = m.new_map(ax=212, ...)
is equivalent to:
>>> m = Maps(ax=211)
>>> m2 = Maps(f=m.f, ax=212, ...)
Parameters
----------
ax : int, list, tuple, matplotlib.Axes, matplotlib.gridspec.SubplotSpec or None
Explicitly specify the position of the axes or use already existing axes.
Possible values are:
- None:
Initialize a new axes at the center of the figure (the default)
- A tuple of 4 floats (*left*, *bottom*, *width*, *height*)
The absolute position of the axis in relative figure-coordinates
(e.g. in the range [0 , 1])
NOTE: since the axis-size is dependent on the plot-extent, the size of
the map will be adjusted to fit in the provided bounding-box.
- A tuple of 3 integers (*nrows*, *ncols*, *index*)
The map will be positioned at the *index* position of a grid
with *nrows* rows and *ncols* columns. *index* starts at 1 in the
upper left corner and increases to the right. *index* can also be
a two-tuple specifying the (*first*, *last*) indices (1-based, and
including *last*) of the subplot, e.g., ``ax = (3, 1, (1, 2))``
makes a map that spans the upper 2/3 of the figure.
- A 3-digit integer
Same as using a tuple of three single-digit integers.
(e.g. 111 is the same as (1, 1, 1) )
- `matplotilb.gridspec.SubplotSpec`:
Use the SubplotSpec for initializing the axes.
- `matplotilb.Axes`:
Directly use the provided figure and axes instances for plotting.
NOTE: The axes MUST be a geo-axes with `m.crs_plot` projection!
keep_on_top : bool
If True, this map will be drawn on top of all other axes.
(e.g. similar to InsetMaps)
The default is False.
preferred_wms_service : str, optional
Set the preferred way for accessing WebMap services if both WMS and WMTS
capabilities are possible.
The default is "wms"
inherit_data, inherit_classification, inherit_shape : bool
Indicator if the corresponding properties should be inherited from
the parent Maps-object.
By default only the shape is inherited.
For more details, see :py:meth:`Maps.inherit_data` and
:py:meth:`Maps.inherit_classification`
kwargs :
additional kwargs are passed to `matplotlib.pyplot.figure()`
- e.g. figsize=(10,5)
Returns
-------
m: EOmaps.Maps
The Maps object representing the new map.
"""
m2 = Maps(f=self.f, ax=ax, **kwargs)
if inherit_data:
m2.inherit_data(self)
if inherit_classification:
m2.inherit_classification(self)
if inherit_shape and self._shape_assigned:
getattr(m2.set_shape, self.shape.name)(**self.shape._initargs)
if np.allclose(self.ax.bbox.bounds, m2.ax.bbox.bounds):
_log.warning(
"EOmaps:The new map overlaps exactly with the parent map! "
"Use `ax=...` or the LayoutEditor to adjust the position of the map."
)
if keep_on_top is True:
m2.ax.set_label("inset_map")
spine = m2.ax.spines["geo"]
if spine in self.BM._bg_artists.get("___SPINES__", []):
self.BM.remove_bg_artist(spine, layer="___SPINES__")
if spine not in self.BM._bg_artists.get("__inset___SPINES__", []):
self.BM.add_bg_artist(spine, layer="__inset___SPINES__")
return m2
def new_layer(
self,
layer=None,
inherit_data=False,
inherit_classification=False,
inherit_shape=True,
**kwargs,
):
"""
Create a new Maps-object that shares the same plot-axes.
Parameters
----------
layer : int, str or None
The name of the layer at which map-features are plotted.
- If "all": the corresponding feature will be added to ALL layers
- If None, the layer of the parent object is used.
The default is None.
inherit_data, inherit_classification, inherit_shape : bool
Indicator if the corresponding properties should be inherited from
the parent Maps-object.
By default only the shape is inherited.
For more details, see :py:meth:`Maps.inherit_data` and
:py:meth:`Maps.inherit_classification`
Returns
-------
eomaps.Maps
A connected copy of the Maps-object that shares the same plot-axes.
Examples
--------
Create a new Maps-object **on an existing layer**
>>> from eomaps import Maps
>>> m = Maps(layer="base") # m.layer == "base"
>>> m2 = m.new_layer() # m2.layer == "base"
Create a new Maps-object representing a **new layer**
>>> from eomaps import Maps
>>> m = Maps(layer="base") # m.layer == "base"
>>> m2 = m.new_layer("a new layer") # m2.layer == "a new layer"
Create a new layer and immediately delete it after it has been exported.
(useful to free memory if a lot of layers are be exported)
>>> from eomaps import Maps
>>> m = Maps(layer="base")
>>> with m.new_layer("a new layer") as m2:
>>> ...
>>> m2.show() # make the layer visible
>>> m2.savefig(...) # save it as an image
See Also
--------
Maps.copy : general way for copying Maps objects
"""
depreciated_names = [
("copy_data_specs", "inherit_data"),
("copy_classify_specs", "inherit_classification"),
("copy_shape", "inherit_shape"),
]
for old, new in depreciated_names:
if old in kwargs:
from warnings import warn
warn(
f"EOmaps: Using '{old}' is depreciated! Use '{new}' instead! "
"NOTE: Datasets are now inherited (e.g. shared) and not copied. "
"To explicitly copy attributes, see m.copy(...)!",
category=FutureWarning,
stacklevel=2,
)
inherit_data = kwargs.get("copy_data_specs", inherit_data)
inherit_classification = kwargs.get(
"copy_classify_specs", inherit_classification
)
inherit_shape = kwargs.get("copy_shape", inherit_shape)
if layer is None:
layer = copy.deepcopy(self.layer)
else:
layer = str(layer)
if len(layer) == 0:
raise SyntaxError(
"EOmaps: Unable to create a layer with an empty layer-name!"
)
m = self.copy(
data_specs=False,
classify_specs=False,
shape=False,
ax=self.ax,
layer=layer,
)
if inherit_data:
m.inherit_data(self)
if inherit_classification:
m.inherit_classification(self)
if inherit_shape and self._shape_assigned:
getattr(m.set_shape, self.shape.name)(**self.shape._initargs)
# make sure the new layer does not attempt to reset the extent if
# it has already been set on the parent layer
m._set_extent_on_plot = self._set_extent_on_plot
# re-initialize all sliders and buttons to include the new layer
self.util._reinit_widgets()
# share the companion-widget with the parent
m._companion_widget = self._companion_widget
return m
def new_inset_map(
self,
xy=(45, 45),
xy_crs=4326,
radius=5,
radius_crs=None,
plot_position=(0.5, 0.5),
plot_size=0.5,
inset_crs=4326,
layer=None,
boundary=True,
background_color="w",
shape="ellipses",
indicate_extent=True,
indicator_line=False,
):
"""
Create a new (empty) inset-map that shows a zoomed-in view on a given extent.
The returned Maps-object can then be used to populate the inset-map with
features, datasets etc.
See examples below on how to use inset-maps.
Note
----
- By default NO features are added to the inset-map!
Use it just like any other Maps-object to add features or plot datasets!
- Zooming is disabled on inset-maps for now due to issues with zoom-events on
overlapping axes.
- Non-rectangular cropping of WebMap services is not yet supported.
(e.g. use "rectangles" as shape and the native CRS of the WebMap service
for the inset map.)
Parameters
----------
xy : tuple, optional
The center-coordinates of the area to indicate.
(provided in the xy_crs projection)
The default is (45., 45.).
xy_crs : any, optional
The crs used for specifying the center position of the inset-map.
(can be any crs definition supported by PyProj)
The default is 4326 (e.g. lon/lat).
radius : float or tuple, optional
The radius of the extent to indicate.
(provided in units of the radius_crs projection)
The default is 5.
radius_crs : None or a crs-definition, optional
The crs used for specifying the radius. (can be any crs definition
supported by PyProj)
- If None: The crs provided as "xy_crs" is used
- If shape == "geod_circles", "radius_crs" must be None since the radius
of a geodesic circle is defined in meters!
The default is None.
plot_position : tuple, optional
The center-position of the inset map in relative units (0-1) with respect to
the figure size. The default is (.5,.5).
plot_size : float, optional
The relative size of the inset-map compared to the figure width.
The default is 0.5.
inset_crs : any, optional
The crs that is used in the inset-map.
The default is 4326.
layer : str or None, optional
The layer associated with the inset-map.
If None (the default), the layer of the Maps-object used to create
the inset-map is used.
boundary: bool, str or dict, optional
- If True: indicate the boundary of the inset-map with default colors
(e.g.: {"ec":"r", "lw":2})
- If False: don't add edgecolors to the boundary of the inset-map
- If a string is provided, it is identified as the edge-color of the
boundary (e.g. any named matplotlib color like "r", "g", "darkblue"...)
- if dict: use the provided values for "ec" (e.g. edgecolor) and
"lw" (e.g. linewidth)
The default is True.
background_color: str, tuple or None
The background color to use.
- if str: a matplotlib color identifier (e.g. "r", "#162347")
- if tuple: a RGB or RGBA tuple (values must be in the range 0-1)
- If None, no background patch will be drawn (e.g. transparent)
The default is "w" (e.g. white)
shape : str, optional
The shape to use. Can be either "ellipses", "rectangles" or "geod_circles".
The default is "ellipses".
indicate_extent : bool or dict, optional
- If True: add a polygon representing the inset-extent to the parent map.
- If a dict is provided, it will be used to update the appearance of the
added polygon (e.g. facecolor, edgecolor, linewidth etc.)
NOTE: you can also use `m_inset.add_extent_indicator(...)` to manually
indicate the inset-shape on arbitrary Maps-objects.
The default is True.
indicator_line : bool or dict, optional
- If True: add a line that connects the inset-map to the indicated extent
on the parent map
- If a dict is provided, it is used to update the appearance of the line
(e.g. c="r", lw=2, ...)
NOTE: you can also use `m_inset.add_indicator_line(...)` to manually
indicate the inset-shape on arbitrary Maps-objects.
The default is False.
Returns
-------
m : eomaps.inset_maps.InsetMaps
A InsetMaps-object of the inset-map.
(you can use it just like any other Maps-object!)
See Also
--------
Maps.add_extent_indicator : Indicate inset-extent on another map (as polygon).
Maps.set_inset_position : Set the (center) position and size of the inset-map.
Examples
--------
Simple example:
>>> m = Maps()
>>> m.add_feature.preset.coastline()
>>> m2 = m.new_inset_map(xy=(45, 45), radius=10,
>>> plot_position=(.3, .5), plot_size=.7)
>>> m2.add_feature.preset.ocean()
... a bit more complexity:
>>> m = Maps(Maps.CRS.Orthographic())
>>> m.add_feature.preset.coastline() # add some coastlines
>>> m2 = m.new_inset_map(xy=(5, 45),
>>> xy_crs=4326,
>>> shape="geod_circles",
>>> radius=1000000,
>>> plot_position=(.3, .4),
>>> plot_size=.5,
>>> inset_crs=3035,
>>> edgecolor="g",
>>> indicate_extent=False)
>>>
>>> m2.add_feature.preset.coastline()
>>> m2.add_feature.preset.ocean()
>>> m2.add_feature.preset.land()
>>> m2.set_data([1, 2, 3], [5, 6, 7], [45, 46, 47], crs=4326)
>>> m2.plot_map()
>>> m2.add_annotation(ID=1)
>>> m2.add_extent_indicator(m, ec="g", fc=(0,1,0,.25))
Multi-layer inset-maps:
>>> m = Maps(layer="first")
>>> m.add_feature.preset.coastline()
>>> m3 = m.new_layer("second")
>>> m3.add_feature.preset.ocean()
>>> # create an inset-map on the "first" layer
>>> m2 = m.new_inset_map(layer="first")
>>> m2.add_feature.preset.coastline()
>>> # create a new layer of the inset-map that will be
>>> # visible if the "second" layer is visible
>>> m3 = m2.new_layer(layer="second")
>>> m3.add_feature.preset.coastline()
>>> m3.add_feature.preset.land()
>>> m.util.layer_selector()
"""
# to avoid circular imports
from .inset_maps import InsetMaps
m2 = InsetMaps(
parent=self,
crs=inset_crs,
layer=layer,
xy=xy,
radius=radius,
plot_position=plot_position,
plot_size=plot_size,
xy_crs=xy_crs,
radius_crs=radius_crs,
boundary=boundary,
background_color=background_color,
shape=shape,
indicate_extent=indicate_extent,
indicator_line=indicator_line,
)
return m2
def set_data(
self,
data=None,
x=None,
y=None,
crs=None,
encoding=None,
cpos="c",
cpos_radius=None,
parameter=None,
):
"""
Set the properties of the dataset you want to plot.
Use this function to update multiple data-specs in one go
Alternatively you can set the data-specifications via
>>> m.data_specs.< property > = ...`
Parameters
----------
data : array-like
The data of the Maps-object.
Accepted inputs are:
- a pandas.DataFrame with the coordinates and the data-values
- a pandas.Series with only the data-values
- a 1D or 2D numpy-array with the data-values
- a 1D list of data values
x, y : array-like or str, optional
Specify the coordinates associated with the provided data.
Accepted inputs are:
- a string (corresponding to the column-names of the `pandas.DataFrame`)
- ONLY if "data" is provided as a pandas.DataFrame!
- a pandas.Series
- a 1D or 2D numpy-array
- a 1D list
The default is "lon" and "lat".
crs : int, dict or str
The coordinate-system of the provided coordinates.
Can be one of:
- PROJ string
- Dictionary of PROJ parameters
- PROJ keyword arguments for parameters
- JSON string with PROJ parameters
- CRS WKT string
- An authority string [i.e. 'epsg:4326']
- An EPSG integer code [i.e. 4326]
- A tuple of ("auth_name": "auth_code") [i.e ('epsg', '4326')]
- An object with a `to_wkt` method.
- A :class:`pyproj.crs.CRS` class
(see `pyproj.CRS.from_user_input` for more details)
The default is 4326 (e.g. geographic lon/lat crs)
parameter : str, optional
MANDATORY IF a pandas.DataFrame that specifies both the coordinates
and the data-values is provided as `data`!
The name of the column that should be used as parameter.
If None, the first column (despite of the columns assigned as "x" and "y")
will be used. The default is None.
encoding : dict or False, optional
A dict containing the encoding information in case the data is provided as
encoded values (useful to avoid decoding large integer-encoded datasets).
If provided, the data will be decoded "on-demand" with respect to the
provided "scale_factor" and "add_offset" according to the formula:
>>> actual_value = encoding["add_offset"] + encoding["scale_factor"] * value
Note: Colorbars and pick-callbakcs will use the encoding-information to
display the actual data-values!
If False, no value-transformation is performed.
The default is False
cpos : str, optional
Indicator if the provided x-y coordinates correspond to the center ("c"),
upper-left corner ("ul"), lower-left corner ("ll") etc. of the pixel.
If any value other than "c" is provided, a "cpos_radius" must be set!
The default is "c".
cpos_radius : int or tuple, optional
The pixel-radius (in the input-crs) that will be used to set the
center-position of the provided data.
If a number is provided, the pixels are treated as squares.
If a tuple (rx, ry) is provided, the pixels are treated as rectangles.
The default is None.
Examples
--------
- using a single `pandas.DataFrame`
>>> data = pd.DataFrame(dict(lon=[...], lat=[...], a=[...], b=[...]))
>>> m.set_data(data, x="lon", y="lat", parameter="a", crs=4326)
- using individual `pandas.Series`
>>> lon, lat, vals = pd.Series([...]), pd.Series([...]), pd.Series([...])
>>> m.set_data(vals, x=lon, y=lat, crs=4326)
- using 1D lists
>>> lon, lat, vals = [...], [...], [...]