-
Notifications
You must be signed in to change notification settings - Fork 4
/
plotting.py
1303 lines (1148 loc) · 40.6 KB
/
plotting.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
"""This module contains all the plotting methods for PastaStore.
Pastastore comes with a number helpful plotting methods to quickly
visualize time series or the locations of the time series contained in the
store. Plotting time series or data availability is available through the
`plots` attribute of the PastaStore object. Plotting locations of time series
or model statistics on maps is available through the `maps` attribute.
For example, if we have a :class:`pastastore.PastaStore` called `pstore`
linking to an existing database, the plot and map methods are available as
follows::
pstore.plots.oseries()
ax = pstore.maps.oseries()
pstore.maps.add_background_map(ax) # for adding a background map
"""
from collections.abc import Iterable
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pastas as ps
from matplotlib import patheffects
from matplotlib.collections import LineCollection
from matplotlib.colors import BoundaryNorm, LogNorm
from matplotlib.lines import Line2D
from mpl_toolkits.axes_grid1 import make_axes_locatable
class Plots:
"""Plot class for Pastastore.
Allows plotting of time series and data availability.
"""
def __init__(self, pstore):
"""Initialize Plots class for Pastastore.
Parameters
----------
pstore : pastastore.Pastastore
Pastastore object
"""
self.pstore = pstore
def _timeseries(
self,
libname,
names=None,
ax=None,
split=False,
figsize=(10, 5),
progressbar=True,
**kwargs,
):
"""Internal method to plot time series from pastastore.
Parameters
----------
libname : str
name of the library to obtain time series from (oseries
or stresses)
names : list of str, optional
list of time series names to plot, by default None
ax : matplotlib.Axes, optional
pass axes object to plot on existing axes, by default None,
which creates a new figure
split : bool, optional
create a separate subplot for each time series, by default False.
A maximum of 20 time series is supported when split=True.
figsize : tuple, optional
figure size, by default (10, 5)
progressbar : bool, optional
show progressbar when loading time series from store,
by default True
Returns
-------
ax : matplotlib.Axes
axes handle
Raises
------
ValueError
split=True is only supported if there are less than 20 time series
to plot.
"""
names = self.pstore.conn._parse_names(names, libname)
if len(names) > 20 and split:
raise ValueError(
"More than 20 time series leads to too many "
"subplots, set split=False."
)
if ax is None:
if split:
fig, axes = plt.subplots(len(names), 1, sharex=True, figsize=figsize)
else:
fig, axes = plt.subplots(1, 1, figsize=figsize)
else:
axes = ax
if isinstance(axes, Iterable):
fig = axes[0].figure
else:
fig = axes.figure
tsdict = self.pstore.conn._get_series(
libname, names, progressbar=progressbar, squeeze=False
)
for i, (n, ts) in enumerate(tsdict.items()):
if split and ax is None:
iax = axes[i]
elif ax is None:
iax = axes
else:
iax = ax
iax.plot(ts.index, ts.squeeze(), label=n, **kwargs)
if split:
iax.legend(loc="best", fontsize="x-small")
if not split:
axes.legend(loc=(0, 1), frameon=False, ncol=7, fontsize="x-small")
fig.tight_layout()
return axes
def oseries(self, names=None, ax=None, split=False, figsize=(10, 5), **kwargs):
"""Plot oseries.
Parameters
----------
names : list of str, optional
list of oseries names to plot, by default None, which loads
all oseries from store
ax : matplotlib.Axes, optional
pass axes object to plot oseries on existing figure,
by default None, in which case a new figure is created
split : bool, optional
create a separate subplot for each time series, by default False.
A maximum of 20 time series is supported when split=True.
figsize : tuple, optional
figure size, by default (10, 5)
Returns
-------
ax : matplotlib.Axes
axes handle
"""
return self._timeseries(
"oseries",
names=names,
ax=ax,
split=split,
figsize=figsize,
**kwargs,
)
def stresses(
self,
names=None,
kind=None,
ax=None,
split=False,
figsize=(10, 5),
**kwargs,
):
"""Plot stresses.
Parameters
----------
names : list of str, optional
list of oseries names to plot, by default None, which loads
all oseries from store
kind : str, optional
only plot stresses of a certain kind, by default None, which
includes all stresses
ax : matplotlib.Axes, optional
pass axes object to plot oseries on existing figure,
by default None, in which case a new figure is created
split : bool, optional
create a separate subplot for each time series, by default False.
A maximum of 20 time series is supported when split=True.
figsize : tuple, optional
figure size, by default (10, 5)
Returns
-------
ax : matplotlib.Axes
axes handle
"""
names = self.pstore.conn._parse_names(names, "stresses")
masknames = self.pstore.stresses.index.isin(names)
stresses = self.pstore.stresses.loc[masknames]
if kind:
mask = stresses["kind"] == kind
names = stresses.loc[mask].index.to_list()
return self._timeseries(
"stresses",
names=names,
ax=ax,
split=split,
figsize=figsize,
**kwargs,
)
def data_availability(
self,
libname,
names=None,
kind=None,
intervals=None,
ignore=("second", "minute", "14 days"),
ax=None,
cax=None,
normtype="log",
cmap="viridis_r",
set_yticks=False,
figsize=(10, 8),
progressbar=True,
dropna=True,
**kwargs,
):
"""Plot the data-availability for multiple time series in pastastore.
Parameters
----------
libname : str
name of library to get time series from (oseries or stresses)
names : list, optional
specify names in a list to plot data availability for certain
time series
kind : str, optional
if library is stresses, kind can be specified to obtain only
stresses of a specific kind
intervals: dict, optional
A dict with frequencies as keys and number of seconds as values
ignore : list, optional
A list with frequencies in intervals to ignore
ax: matplotlib Axes, optional
pass axes object to plot data availability on existing figure. by
default None, in which case a new figure is created
cax: matplotlib Axes, optional
pass object axes to plot the colorbar on. by default None, which
gives default Maptlotlib behavior
normtype : str, optional
Determines the type of color normalisations, default is 'log'
cmap : str, optional
A reference to a matplotlib colormap
set_yticks : bool, optional
Set the names of the series as yticks
figsize : tuple, optional
The size of the new figure in inches (h,v)
progressbar : bool
Show progressbar
dropna : bool
Do not show NaNs as available data
kwargs : dict, optional
Extra arguments are passed to matplotlib.pyplot.subplots()
Returns
-------
ax : matplotlib Axes
The axes in which the data-availability is plotted
"""
names = self.pstore.conn._parse_names(names, libname)
if libname == "stresses":
masknames = self.pstore.stresses.index.isin(names)
stresses = self.pstore.stresses.loc[masknames]
if kind:
mask = stresses["kind"] == kind
names = stresses.loc[mask].index.to_list()
series = self.pstore.conn._get_series(
libname, names, progressbar=progressbar, squeeze=False
).values()
ax = self._data_availability(
series,
names=names,
intervals=intervals,
ignore=ignore,
ax=ax,
cax=cax,
normtype=normtype,
cmap=cmap,
set_yticks=set_yticks,
figsize=figsize,
dropna=dropna,
**kwargs,
)
return ax
@staticmethod
def _data_availability(
series,
names=None,
intervals=None,
ignore=("second", "minute", "14 days"),
ax=None,
cax=None,
normtype="log",
cmap="viridis_r",
set_yticks=False,
figsize=(10, 8),
dropna=True,
**kwargs,
):
"""Plot the data-availability for a list of time series.
Parameters
----------
libname : list of pandas.Series
list of series to plot data availability for
names : list, optional
specify names of series, default is None in which case names
will be taken from series themselves.
kind : str, optional
if library is stresses, kind can be specified to obtain only
stresses of a specific kind
intervals: dict, optional
A dict with frequencies as keys and number of seconds as values
ignore : list, optional
A list with frequencies in intervals to ignore
ax: matplotlib Axes, optional
pass axes object to plot data availability on existing figure. by
default None, in which case a new figure is created
cax: matplotlib Axes, optional
pass object axes to plot the colorbar on. by default None, which
gives default Maptlotlib behavior
normtype : str, optional
Determines the type of color normalisations, default is 'log'
cmap : str, optional
A reference to a matplotlib colormap
set_yticks : bool, optional
Set the names of the series as yticks
figsize : tuple, optional
The size of the new figure in inches (h,v)
progressbar : bool
Show progressbar
dropna : bool
Do not show NaNs as available data
kwargs : dict, optional
Extra arguments are passed to matplotlib.pyplot.subplots()
Returns
-------
ax : matplotlib Axes
The axes in which the data-availability is plotted
"""
# a good colormap is cmap='RdYlGn_r' or 'cubehelix'
if ax is None:
fig, ax = plt.subplots(figsize=figsize, **kwargs)
else:
fig = ax.get_figure()
ax.invert_yaxis()
if intervals is None:
intervals = {
"second": 1,
"minute": 60,
"hour": 60 * 60,
"day": 60 * 60 * 24,
"week": 60 * 60 * 24 * 7,
"14 days": 60 * 60 * 24 * 14,
"month": 60 * 60 * 24 * 31,
"quarter": 60 * 60 * 24 * 31 * 4,
"year": 60 * 60 * 24 * 366,
}
for i in ignore:
if i in intervals:
intervals.pop(i)
bounds = np.array([intervals[i] for i in intervals])
bounds = bounds.astype(float) * (10**9)
labels = intervals.keys()
if normtype == "log":
norm = LogNorm(vmin=bounds[0], vmax=bounds[-1])
else:
norm = BoundaryNorm(boundaries=bounds, ncolors=256)
cmap = plt.get_cmap(cmap, 256)
cmap.set_over((1.0, 1.0, 1.0))
for i, s in enumerate(series):
if not s.empty:
if dropna:
s = s.dropna()
pc = ax.pcolormesh(
s.index,
[i, i + 1],
[np.diff(s.index).astype(float)],
norm=norm,
cmap=cmap,
linewidth=0,
rasterized=True,
)
# make a colorbar in an ax on the
# right side, then set the current axes to ax again
cb = fig.colorbar(pc, ax=ax, cax=cax, extend="both")
cb.set_ticks(bounds)
cb.ax.set_yticklabels(labels)
cb.ax.minorticks_off()
if set_yticks:
ax.set_yticks(np.arange(0.5, len(series) + 0.5))
if names is None:
names = [s.name for s in series]
ax.set_yticklabels(names)
else:
ax.set_ylabel("Timeseries (-)")
ax.grid()
return ax
def cumulative_hist(
self,
statistic="rsq",
modelnames=None,
extend=False,
ax=None,
figsize=(6, 6),
label=None,
legend=True,
):
"""Plot a cumulative step histogram for a model statistic.
Parameters
----------
statistic: str
name of the statistic, e.g. "evp" or "rmse", by default "rsq"
modelnames: list of str, optional
modelnames to plot statistic for, by default None, which
uses all models in the store
extend: bool, optional
force extend the stats Series with a dummy value to move the
horizontal line outside figure bounds. If True the results
are skewed a bit, especially if number of models is low.
ax: matplotlib.Axes, optional
axes to plot histogram, by default None which creates an Axes
figsize: tuple, optional
figure size, by default (6,6)
label: str, optional
label for the legend, by default None, which shows the number
of models
legend: bool, optional
show legend, by default True
Returns
-------
ax : matplotlib Axes
The axes in which the cumulative histogram is plotted
"""
statsdf = self.pstore.get_statistics(
[statistic], modelnames=modelnames, progressbar=False
)
if ax is None:
_, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_xticks(np.linspace(0, 1, 11))
ax.set_xlim(0, 1)
ax.set_ylabel(statistic)
ax.set_xlabel("Density")
ax.set_title("Cumulative Step Histogram")
if statistic == "evp":
ax.set_yticks(np.linspace(0, 100, 11))
if extend:
statsdf = statsdf.append(pd.Series(100, index=["dummy"]))
ax.set_ylim(0, 100)
else:
ax.set_ylim(0, statsdf.max())
elif statistic in ("rsq", "nse", "kge_2012"):
ax.set_yticks(np.linspace(0, 1, 11))
if extend:
statsdf = statsdf.append(pd.Series(1, index=["dummy"]))
statsdf[statsdf < 0] = 0
ax.set_ylim(0, 1)
else:
ax.set_ylim(0, statsdf.max())
elif statistic in ("aic", "bic"):
ax.set_ylim(statsdf.min(), statsdf.max())
else:
if extend:
statsdf = statsdf.append(pd.Series(0, index=["dummy"]))
ax.set_ylim(0, statsdf.max())
if label is None:
if extend:
label = f"No. Models = {len(statsdf)-1}"
else:
label = f"No. Models = {len(statsdf)}"
statsdf.hist(
ax=ax,
bins=len(statsdf),
density=True,
cumulative=True,
histtype="step",
orientation="horizontal",
label=label,
)
if legend:
ax.legend(loc=4)
return ax
class Maps:
"""Map Class for PastaStore.
Allows plotting locations and model statistics on maps.
Usage
-----
Example usage of the maps methods: :
>> > ax = pstore.maps.oseries() # plot oseries locations
>> > pstore.maps.add_background_map(ax) # add background map
"""
def __init__(self, pstore):
"""Initialize Plots class for Pastastore.
Parameters
----------
pstore: pastastore.Pastastore
Pastastore object
"""
self.pstore = pstore
def stresses(
self,
names=None,
kind=None,
labels=True,
adjust=False,
figsize=(10, 8),
backgroundmap=False,
**kwargs,
):
"""Plot stresses locations on map.
Parameters
----------
names : list of str, optional
list of names to plot
kind: str, optional
if passed, only plot stresses of a specific kind, default is None
which plots all stresses.
labels: bool, optional
label models, by default True
adjust: bool, optional
automated smart label placement using adjustText, by default False
ax : matplotlib.Axes, optional
axes handle, if not provided a new figure is created.
figsize: tuple, optional
figure size, by default(10, 8)
backgroundmap: bool, optional
if True, add background map (default CRS is EPSG:28992) with default tiles
by OpenStreetMap.Mapnik. Default option is False.
Returns
-------
ax: matplotlib.Axes
axes object
See also
--------
self.add_background_map
"""
if names is not None:
df = self.pstore.stresses.loc[names]
else:
df = self.pstore.stresses
if kind is not None:
if isinstance(kind, str):
kind = [kind]
mask = df["kind"].isin(kind)
stresses = df[mask]
else:
stresses = df
mask0 = (stresses["x"] != 0.0) | (stresses["y"] != 0.0)
c = stresses.loc[mask0, "kind"]
kind_to_color = {k: f"C{i}" for i, k in enumerate(c.unique())}
c = c.apply(lambda k: kind_to_color[k])
r = self._plotmap_dataframe(stresses.loc[mask0], c=c, figsize=figsize, **kwargs)
if "ax" in kwargs:
ax = kwargs["ax"]
else:
ax = r
if labels:
self.add_labels(stresses, ax, adjust=adjust)
if backgroundmap:
self.add_background_map(ax)
return ax
def oseries(
self,
names=None,
labels=True,
adjust=False,
figsize=(10, 8),
backgroundmap=False,
**kwargs,
):
"""Plot oseries locations on map.
Parameters
----------
names: list, optional
oseries names, by default None which plots all oseries locations
labels: bool, optional
label models, by default True
adjust: bool, optional
automated smart label placement using adjustText, by default False
figsize: tuple, optional
figure size, by default(10, 8)
backgroundmap: bool, optional
if True, add background map (default CRS is EPSG:28992) with default tiles
by OpenStreetMap.Mapnik. Default option is False.
Returns
-------
ax: matplotlib.Axes
axes object
See also
--------
self.add_background_map
"""
names = self.pstore.conn._parse_names(names, "oseries")
oseries = self.pstore.oseries.loc[names]
mask0 = (oseries["x"] != 0.0) | (oseries["y"] != 0.0)
r = self._plotmap_dataframe(oseries.loc[mask0], figsize=figsize, **kwargs)
if "ax" in kwargs:
ax = kwargs["ax"]
else:
ax = r
if labels:
self.add_labels(oseries, ax, adjust=adjust)
if backgroundmap:
self.add_background_map(ax)
return ax
def models(
self, labels=True, adjust=False, figsize=(10, 8), backgroundmap=False, **kwargs
):
"""Plot model locations on map.
Parameters
----------
labels: bool, optional
label models, by default True
adjust: bool, optional
automated smart label placement using adjustText, by default False
ax : matplotlib.Axes, optional
axes handle, if not provided a new figure is created.
figsize: tuple, optional
figure size, by default(10, 8)
backgroundmap: bool, optional
if True, add background map (default CRS is EPSG:28992) with default tiles
by OpenStreetMap.Mapnik. Default option is False.
Returns
-------
ax: matplotlib.Axes
axes object
See also
--------
self.add_background_map
"""
model_oseries = [
self.pstore.get_models(m, return_dict=True)["oseries"]["name"]
for m in self.pstore.model_names
]
models = self.pstore.oseries.loc[model_oseries]
models.index = self.pstore.model_names
# mask out 0.0 coordinates
mask0 = (models["x"] != 0.0) | (models["y"] != 0.0)
r = self._plotmap_dataframe(models.loc[mask0], figsize=figsize, **kwargs)
if "ax" in kwargs:
ax = kwargs["ax"]
else:
ax = r
if labels:
self.add_labels(models, ax, adjust=adjust)
if backgroundmap:
self.add_background_map(ax)
return ax
def modelstat(
self,
statistic,
label=True,
adjust=False,
cmap="viridis",
norm=None,
vmin=None,
vmax=None,
figsize=(10, 8),
backgroundmap=False,
**kwargs,
):
"""Plot model statistic on map.
Parameters
----------
statistic: str
name of the statistic, e.g. "evp" or "aic"
label: bool, optional
label points, by default True
adjust: bool, optional
automated smart label placement using adjustText, by default False
cmap: str or colormap, optional
(name of) the colormap, by default "viridis"
norm: norm, optional
normalization for colorbar, by default None
vmin: float, optional
vmin for colorbar, by default None
vmax: float, optional
vmax for colorbar, by default None
ax : matplotlib.Axes, optional
axes handle, if not provided a new figure is created.
figsize: tuple, optional
figuresize, by default(10, 8)
backgroundmap: bool, optional
if True, add background map (default CRS is EPSG:28992) with default tiles
by OpenStreetMap.Mapnik. Default option is False.
Returns
-------
ax: matplotlib.Axes
axes object
See also
--------
self.add_background_map
"""
statsdf = self.pstore.get_statistics([statistic], progressbar=False).to_frame()
statsdf["oseries"] = [
self.pstore.get_models(m, return_dict=True)["oseries"]["name"]
for m in statsdf.index
]
statsdf = statsdf.reset_index().set_index("oseries")
df = statsdf.join(self.pstore.oseries, how="left")
scatter_kwargs = {
"cmap": cmap,
"norm": norm,
"vmin": vmin,
"vmax": vmax,
"edgecolors": "w",
"linewidths": 0.7,
}
scatter_kwargs.update(kwargs)
ax = self._plotmap_dataframe(
df, column=statistic, figsize=figsize, **scatter_kwargs
)
if label:
df.set_index("index", inplace=True)
self.add_labels(df, ax, adjust=adjust)
if backgroundmap:
self.add_background_map(ax)
return ax
@staticmethod
def _plotmap_dataframe(
df,
x="x",
y="y",
column=None,
colorbar=True,
ax=None,
figsize=(10, 8),
**kwargs,
):
"""Internal method for plotting dataframe with point locations.
Can be called directly for more control over plot characteristics.
Parameters
----------
df : pandas.DataFrame
DataFrame containing coordinates and data to plot, with
index providing names for each location
x : str, optional
name of the column with x - coordinate data, by default "x"
y : str, optional
name of the column with y - coordinate data, by default "y"
column : str, optional
name of the column containing data used for determining the
color of each point, by default None (all one color)
colorbar : bool, optional
show colorbar, only if column is provided, by default True
ax : matplotlib Axes
axes handle to plot dataframe, optional, default is None
which creates a new figure
figsize : tuple, optional
figure size, by default(10, 8)
**kwargs :
dictionary containing keyword arguments for ax.scatter,
by default None
Returns
-------
ax : matplotlib.Axes
axes object, returned if ax is None
sc : scatter handle
scatter plot handle, returned if ax is not None
"""
if ax is None:
return_scatter = False
fig, ax = plt.subplots(figsize=figsize)
else:
return_scatter = True
fig = ax.figure
# set default size and marker if not passed
if kwargs:
s = kwargs.pop("s", 70)
marker = kwargs.pop("marker", "o")
else:
s = 70
marker = "o"
kwargs = {}
# if column is passed for coloring pts
if column:
c = df[column]
if "cmap" not in kwargs:
kwargs["cmap"] = "viridis"
else:
c = kwargs.pop("c", None)
sc = ax.scatter(df[x], df[y], marker=marker, s=s, c=c, **kwargs)
# add colorbar
if column and colorbar:
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="3%", pad=0.05)
cbar = fig.colorbar(sc, ax=ax, cax=cax)
cbar.set_label(column)
# set axes properties
ax.set_xlabel("x")
ax.set_ylabel("y")
for label in ax.get_yticklabels():
label.set_rotation(90)
label.set_verticalalignment("center")
fig.tight_layout()
if return_scatter:
return sc
else:
return ax
def model(
self,
ml,
label=True,
metadata_source="model",
offset=0.0,
ax=None,
figsize=(10, 10),
backgroundmap=False,
):
"""Plot oseries and stresses from one model on a map.
Parameters
----------
ml: str or pastas.Model
pastas model or name of pastas model to plot on map
label: bool, optional, default is True
add labels to points on map
metadata_source: str, optional
whether to obtain metadata from model Timeseries or from
metadata in pastastore("store"), default is "model"
offset : float, optional
add offset to current extent of model time series, useful
for zooming out around models
ax : matplotlib.Axes, optional
axes handle, if not provided a new figure is created.
figsize: tuple, optional
figsize, default is (10, 10)
backgroundmap: bool, optional
if True, add background map (default CRS is EPSG:28992) with default tiles
by OpenStreetMap.Mapnik. Default option is False.
Returns
-------
ax: axes object
axis handle of the resulting figure
See also
--------
self.add_background_map
"""
if isinstance(ml, str):
ml = self.pstore.get_models(ml)
elif not isinstance(ml, ps.Model):
raise TypeError("Pass model name as string or pastas.Model!")
stresses = pd.DataFrame(columns=["x", "y", "stressmodel", "color"])
count = 0
for name, sm in ml.stressmodels.items():
for istress in sm.stress:
if metadata_source == "model":
xi = istress.metadata["x"]
yi = istress.metadata["y"]
elif metadata_source == "store":
imeta = self.pstore.get_metadata(
"stresses", istress.name, as_frame=False
)
xi = imeta.pop("x", np.nan)
yi = imeta.pop("y", np.nan)
else:
raise ValueError(
"metadata_source must be either " "'model' or 'store'!"
)
if np.isnan(xi) or np.isnan(yi):
print(f"No x,y-data for {istress.name}!")
continue
if xi == 0.0 or yi == 0.0:
print(f"x,y-data is 0.0 for {istress.name}, not plotting!")
continue
stresses.loc[istress.name, :] = (xi, yi, name, f"C{count%10}")
count += 1
# create figure
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
else:
fig = ax.figure
# add oseries
osize = 50
oserieslabel = ml.oseries.name
if metadata_source == "model":
xm = float(ml.oseries.metadata["x"])
ym = float(ml.oseries.metadata["y"])
elif metadata_source == "store":
ometa = self.pstore.get_metadata("oseries", ml.oseries.name, as_frame=False)
xm = float(ometa.pop("x", np.nan))
ym = float(ometa.pop("y", np.nan))
else:
raise ValueError("metadata_source must be either " "'model' or 'store'!")
po = ax.scatter(xm, ym, s=osize, marker="o", label=oserieslabel, color="k")
legend_list = [po]
# add stresses
ax.scatter(
stresses["x"],
stresses["y"],
s=50,
c=stresses.color,
marker="o",
edgecolors="k",
linewidths=0.75,
)
# label oseries
if label:
stroke = [patheffects.withStroke(linewidth=3, foreground="w")]
txt = ax.annotate(
text=oserieslabel,
xy=(xm, ym),
fontsize=8,
textcoords="offset points",
xytext=(10, 10),
)
txt.set_path_effects(stroke)