forked from NCAS-CMS/cf-plot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontour.py
More file actions
2259 lines (1950 loc) · 73.3 KB
/
Copy pathcontour.py
File metadata and controls
2259 lines (1950 loc) · 73.3 KB
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
"""Contour plotting module.
Provides the refactored contour plotting interface.
Architecture:
- ContourData: Immutable container for arrays and metadata
- ContourLayout: Manages viewport allocation
- ColourScale: Encapsulates colormap/level logic
- ContourRenderer: Base class for rendering strategy
- MapContourRenderer: Renders to map (Cartopy)
- XYContourRenderer: Renders to Cartesian axes
Module Independence:
This module is currently independent at the module level (no module-level
imports from cfplot.py), though functions do import locally from cfplot
for essential utilities like calculate_levels and axis helpers. This keeps
module boundaries clear while preserving functionality during gradual refactoring.
Future work will move more utilities (calculate_levels, _stimeaxis, etc.)
into standalone modules (see utility.py, state.py) and eliminate even the
function-level cfplot imports.
"""
from __future__ import annotations
from dataclasses import dataclass, replace
import logging
import time
from typing import Any
import cf
import cartopy.crs as ccrs
import matplotlib.colors
import numpy as np
from matplotlib.axes import Axes
from . import utility
from .blockfill import _bfill, _bfill_ugrid
from .colour import apply_colour_scale, get_colour_scale_map
from .colorbar import cbar
from .layout_runtime import (
apply_axes,
ensure_xy_viewport,
maybe_autosave,
set_plot_limits,
)
from .map_runtime import (
MapSet,
_apply_dim_titles,
_apply_map_title,
_apply_map_features,
ensure_map_viewport,
)
from .rotated_runtime import _render_ptype6_rotated_pole
from .state import (
global_blockfill,
global_fill,
global_lines,
plotvars,
)
logger = logging.getLogger(__name__)
def _detect_lon_cyclic(f: "cf.Field", x: "np.ndarray | None") -> bool:
"""Return True when the longitude axis closes on itself at 360°.
Prefers cell bounds from the CF field when available. Falls back to a
centre-point heuristic (range + step ≈ 360°) when bounds are absent.
Returns False for non-1-D or irregular grids (e.g. ORCA).
"""
try:
xdim = f.dim("X", default=None)
if xdim is not None and xdim.has_bounds():
b = xdim.bounds.data.array
if b.ndim == 2:
# Cyclic: right edge of last cell == left edge of first cell + 360°
return abs(float(b[-1, 1]) - float(b[0, 0]) - 360.0) < 1.0
# Fallback: centre-point heuristic — only valid for 1-D lon arrays
if x is not None and x.ndim == 1 and len(x) > 1:
step = (float(x[-1]) - float(x[0])) / (len(x) - 1)
return abs((float(x[-1]) - float(x[0]) + step) - 360.0) < 0.5 * abs(step)
except Exception:
pass
return False
@dataclass(frozen=True)
class ContourData:
"""Read-only contour inputs after extraction and validation.
Holds extracted, validated, and pre-processed arrays ready for rendering.
Immutable by design to prevent unintended state mutations during plotting.
"""
field: np.ndarray
x: np.ndarray | None
y: np.ndarray | None
ptype: int = 0
colorbar_title: str = ""
xlabel: str = ""
ylabel: str = ""
levels: np.ndarray | None = None
mult: int = 0
fmult: float = 1.0
irregular: bool = False
is_ugrid: bool = False
is_orca: bool = False
fill: bool = True
lines: bool = True
blockfill: bool = False
xpole: float | None = None
ypole: float | None = None
x_is_cyclic: bool = False
face_lons: np.ndarray | None = None
face_lats: np.ndarray | None = None
face_connectivity: np.ndarray | None = None
@classmethod
def from_cf_field(
cls,
f: cf.Field,
colorbar_title: str | None,
verbose: bool | None = None,
proj: str = "cyl",
) -> "ContourData":
"""Extract and prepare CF field for contouring."""
(
field,
x,
y,
ptype,
cbar_title,
xlabel,
ylabel,
xpole,
ypole,
) = utility.cf_data_assign(f, colorbar_title, verbose=verbose, proj=proj)
if colorbar_title is not None:
cbar_title = colorbar_title
x_arr = x if x is None else np.asarray(x)
x_is_cyclic = _detect_lon_cyclic(f, x_arr)
irregular = (
np.asanyarray(field).ndim == 1
and x_arr is not None
and y is not None
and np.ndim(x_arr) == 1
and np.ndim(y) == 1
and np.asanyarray(field).size == np.asarray(x_arr).size == np.asarray(y).size
)
if irregular and proj == "cyl":
x_arr = _normalize_longitudes_for_map(x_arr)
return cls(
field=np.asanyarray(field),
x=x_arr,
y=y if y is None else np.asarray(y),
ptype=ptype if ptype is not None else 0,
colorbar_title=cbar_title or "",
xlabel=xlabel or "",
ylabel=ylabel or "",
xpole=utility.to_float_or_none(xpole),
ypole=utility.to_float_or_none(ypole),
x_is_cyclic=x_is_cyclic,
irregular=irregular,
)
@classmethod
def from_arrays(
cls,
field: np.ndarray,
x: np.ndarray | None = None,
y: np.ndarray | None = None,
) -> "ContourData":
"""Create from raw numpy arrays with validation."""
field = np.asanyarray(field)
x = np.asarray(x) if x is not None else np.arange(field.shape[1])
y = np.asarray(y) if y is not None else np.arange(field.shape[0])
# Validate array dimensions - support both 1D coordinates and 2D (e.g., ORCA grids)
if field.ndim not in (1, 2, 3):
raise ValueError(f"Field must be 1D, 2D, or 3D, got shape {field.shape}")
return cls(
field=field,
x=x,
y=y,
ptype=0,
colorbar_title="",
xlabel="",
ylabel="",
)
class ContourLayout:
"""Manage viewport and annotation geometry for contour plots.
Separates concerns: layout calculates space, rendering uses it.
Currently still delegates to legacy gopen/gset/gpos system.
"""
def __init__(self, plotvars: Any):
self.viewport: Axes | None = None
self.colorbar_ax: Axes | None = None
self.title_ax: Axes | None = None
self._plotvars = plotvars
self.colorbar_orientation: str = "horizontal"
self.colorbar_position: list[float] | None = None
def allocate_xy_viewport(
self,
colorbar_orientation: str | None,
colorbar_position: list[float] | None,
) -> "ContourLayout":
"""Reserve viewport for Cartesian/non-map rendering.
Coordinates with plotvars for multi-plot grids.
"""
# Set colorbar orientation
self.colorbar_orientation = colorbar_orientation or "horizontal"
self.colorbar_position = colorbar_position
ensure_xy_viewport()
# Store reference to current axes/map for later use
self.viewport = self._plotvars.runtime.plot
return self
def allocate_map_viewport(
self,
colorbar_orientation: str | None,
colorbar_position: list[float] | None,
) -> "ContourLayout":
"""Reserve viewport for map rendering without map-axis operations.
This intentionally keeps map setup in a dedicated flow where projection
creation (mapset/_set_map) happens after base viewport selection.
"""
self.colorbar_orientation = colorbar_orientation or "horizontal"
self.colorbar_position = colorbar_position
ensure_map_viewport()
self.viewport = self._plotvars.runtime.plot
return self
def allocate(
self,
colorbar_orientation: str | None,
colorbar_position: list[float] | None,
) -> "ContourLayout":
"""Backward-compatible alias for Cartesian viewport allocation."""
return self.allocate_xy_viewport(colorbar_orientation, colorbar_position)
def apply_title(
self,
title: str | None,
dims_title: bool,
fontsize: int | None,
fontweight: str | None,
) -> None:
"""Apply title and dimension titles to plot."""
pv = self._plotvars
runtime = pv.runtime
map_state = pv.map
dec = pv.decoration
if title and title != "":
if runtime.plot_type == 1:
_apply_map_title(
mymap=runtime.mymap,
title=title,
proj=map_state.proj,
boundinglat=map_state.boundinglat,
lon_0=map_state.lon_0,
lonmin=map_state.lonmin,
lonmax=map_state.lonmax,
latmin=map_state.latmin,
latmax=map_state.latmax,
title_fontsize=fontsize or dec.title_fontsize,
title_fontweight=fontweight or dec.title_fontweight,
)
else:
if self.viewport:
self.viewport.set_title(
title,
y=1.03,
fontsize=fontsize or dec.title_fontsize,
fontweight=fontweight or dec.title_fontweight,
)
if dims_title:
_apply_dim_titles(
plot=runtime.plot,
mymap=runtime.mymap,
plot_type=runtime.plot_type,
proj=map_state.proj,
lonmin=map_state.lonmin,
lonmax=map_state.lonmax,
latmin=map_state.latmin,
latmax=map_state.latmax,
axis_label_fontsize=dec.axis_label_fontsize,
axis_label_fontweight=dec.axis_label_fontweight,
title=dims_title if isinstance(dims_title, str) else None,
)
def apply_axis_labels(
self,
xlabel: str | None,
ylabel: str | None,
xticks: Any,
yticks: Any,
xticklabels: Any | None = None,
yticklabels: Any | None = None,
) -> None:
"""Apply axis labels and ticks to plot."""
if self.viewport is None:
return
apply_axes(
plot_type=self._plotvars.runtime.plot_type,
xticks=xticks,
yticks=yticks,
xlabel=xlabel,
ylabel=ylabel,
xticklabels=xticklabels,
yticklabels=yticklabels,
)
class ColourScale:
"""Encapsulate level fitting, colormap selection, and cbar labels.
Replaces the scattered cscale_flag (0/1/2) branching with explicit methods.
"""
def __init__(self, plotvars: Any):
self._plotvars = plotvars
self._levels: np.ndarray | None = None
self._includes_zero: bool = False
self._levels_extend: str = "neither"
def fit_to_levels(
self,
levels: np.ndarray,
includes_zero: bool,
levels_extend: str,
) -> "ColourScale":
"""Fit color scale to contour levels, handling zero if present."""
self._levels = np.asarray(levels)
self._includes_zero = includes_zero
self._levels_extend = levels_extend
scale = self._plotvars.scale
# Replicate legacy cscale_flag == 0 logic (default colour scale).
# If zero is present in levels, split scale1 around zero so
# blue shades are strictly below zero and warm shades above.
if scale.cscale_flag == 0:
col_zero = 0
includes_zero = False
for cval in self._levels:
if not includes_zero:
col_zero += 1
if cval == 0:
includes_zero = True
if includes_zero:
cs_below = col_zero
cs_above = np.size(self._levels) - col_zero + 1
if scale.levels_extend in ("max", "neither"):
cs_below = cs_below - 1
if scale.levels_extend in ("min", "neither"):
cs_above = cs_above - 1
apply_colour_scale(
"scale1",
below=cs_below,
above=cs_above,
uniform=bool(scale.cs_uniform),
)
else:
ncols = np.size(self._levels) + 1
if scale.levels_extend in ("min", "max"):
ncols = ncols - 1
elif scale.levels_extend == "neither":
ncols = ncols - 2
apply_colour_scale("viridis", ncols=ncols)
scale.cscale_flag = 0
# Replicate cscale_flag == 1 logic (user-selected color map, fit to levels)
if scale.cscale_flag == 1:
ncols = np.size(self._levels) + 1
if scale.levels_extend == "min" or scale.levels_extend == "max":
ncols = ncols - 1
if scale.levels_extend == "neither":
ncols = ncols - 2
apply_colour_scale(scale.cs_user, ncols=ncols)
scale.cscale_flag = 1
return self
def get_cmap(self) -> matplotlib.colors.ListedColormap:
"""Get colormap after fitting to levels."""
scale = self._plotvars.scale
colmap = get_colour_scale_map()
cmap = matplotlib.colors.ListedColormap(colmap)
if scale.levels_extend == "min" or scale.levels_extend == "both":
cmap.set_under(scale.cs[0])
if scale.levels_extend == "max" or scale.levels_extend == "both":
cmap.set_over(scale.cs[-1])
return cmap
def colourbar_labels(
self,
levels: np.ndarray,
orientation: str,
n_columns: int,
label_skip: int | None,
custom_labels: list[str] | None,
) -> list[str]:
"""Generate colourbar labels from levels with skip/custom overrides."""
if custom_labels is not None:
return custom_labels
# Legacy default: estimate skip for horizontal colour bars from the
# total character count, and include fewer labels for readability.
if label_skip is None:
if orientation == "horizontal":
nchars = sum(len(str(level)) for level in levels)
label_skip = int(nchars / 80 + 1)
if n_columns > 1:
label_skip = int(nchars * n_columns / 80)
else:
label_skip = 1
if label_skip <= 1:
return [str(level) for level in levels]
if self._includes_zero:
zero_positions = np.where(np.asarray(levels) == 0)[0]
if np.size(zero_positions) > 0:
zero_pos = int(zero_positions[0])
labels = [levels[zero_pos]]
i = zero_pos + label_skip
while i <= len(levels) - 1:
labels = list(np.append(labels, levels[i]))
i += label_skip
i = zero_pos - label_skip
if i >= 0:
while i >= 0:
labels = list(np.append([levels[i]], labels))
i -= label_skip
return self._expand_skipped_labels(labels, label_skip)
labels = [levels[0]]
i = int(label_skip)
while i <= len(levels) - 1:
labels = list(np.append(labels, levels[i]))
i += label_skip
return self._expand_skipped_labels(labels, label_skip)
@staticmethod
def _expand_skipped_labels(labels: list[Any], label_skip: int) -> list[str]:
"""Interleave skipped colour-bar labels with blank placeholders."""
clabels: list[str] = []
for label in labels:
clabels.append(str(label))
if label_skip > 1:
clabels.extend([""] * (label_skip - 1))
return clabels
class ContourRenderer:
"""Base renderer for shared contour drawing responsibilities."""
def __init__(
self,
layout: ContourLayout,
data: ContourData,
colour_scale: ColourScale,
):
self.layout = layout
self.data = data
self.cs = colour_scale
self.frame_artists: list[Any] = []
def render_filled(
self, alpha: float, zorder: int, transform_first: bool | None
) -> None:
"""Render filled contours. Subclass implements plot-type-specific logic."""
_ = (alpha, zorder, transform_first)
def render_blockfill(
self, fast: bool | None, alpha: float, zorder: int
) -> None:
"""Render block-filled contours."""
_ = (fast, alpha, zorder)
def render_lines(
self,
colors: Any,
linewidths: Any,
linestyles: Any,
line_labels: bool,
zero_thick: bool | int,
zorder: int = 1,
) -> None:
"""Render contour lines and labels."""
_ = (colors, linewidths, linestyles, line_labels, zero_thick, zorder)
def render_colorbar(
self,
orientation: str | None,
shrink: float | None,
position: list[float] | None,
fraction: float | None,
thick: float | None,
anchor: float | None,
fontsize: int | None,
fontweight: str | None,
text_up_down: bool,
text_down_up: bool,
drawedges: bool,
labels: list[str] | None = None,
title: str | None = None,
) -> Any:
"""Render colorbar for filled contours."""
_ = (
orientation,
shrink,
position,
fraction,
thick,
anchor,
fontsize,
fontweight,
text_up_down,
text_down_up,
drawedges,
labels,
title,
)
return None
class MapContourRenderer(ContourRenderer):
"""Map renderer specialization for ptype == 1 (lon-lat plots).
Handles Cartopy transformations, coastlines, and polar projections.
"""
def render_filled(
self, alpha: float, zorder: int, transform_first: bool | None
) -> None:
"""Render filled contours on a map with Cartopy."""
if self.data.x is None or self.data.y is None or self.data.levels is None:
return
lons = self.data.x
lats = self.data.y
if self.data.irregular:
field, lons, lats = _window_irregular_map_data(
self.data.field * self.data.fmult,
lons,
lats,
)
runtime = plotvars.runtime
scale = plotvars.scale
cmap = self.cs.get_cmap()
runtime.image = runtime.mymap.tricontourf(
lons,
lats,
field,
self.data.levels,
extend=scale.levels_extend,
cmap=cmap,
norm=scale.norm,
alpha=alpha,
transform=ccrs.PlateCarree(),
zorder=zorder,
)
if hasattr(runtime.image, "collections"):
self.frame_artists.extend(list(runtime.image.collections))
return
if transform_first is None and np.ndim(lons) == 1 and np.ndim(lats) == 1:
if np.size(lons) >= 400:
transform_first = True
if transform_first and np.ndim(lons) == 1 and np.ndim(lats) == 1:
lons, lats = np.meshgrid(lons, lats)
cmap = self.cs.get_cmap()
runtime = plotvars.runtime
scale = plotvars.scale
runtime.image = runtime.mymap.contourf(
lons,
lats,
self.data.field * self.data.fmult,
self.data.levels,
extend=scale.levels_extend,
cmap=cmap,
norm=scale.norm,
alpha=alpha,
transform=ccrs.PlateCarree(),
zorder=zorder,
transform_first=transform_first,
)
if hasattr(runtime.image, "collections"):
self.frame_artists.extend(list(runtime.image.collections))
def render_blockfill(
self, fast: bool | None, alpha: float, zorder: int
) -> None:
"""Render block-filled contours on a map."""
if self.data.levels is None:
return
if self.data.is_ugrid:
if (
self.data.face_lons is None
or self.data.face_lats is None
or self.data.face_connectivity is None
):
return
_bfill_ugrid(
f=self.data.field * self.data.fmult,
face_lons=self.data.face_lons,
face_lats=self.data.face_lats,
face_connectivity=self.data.face_connectivity,
clevs=self.data.levels,
alpha=alpha,
zorder=zorder,
)
return
if self.data.x is None or self.data.y is None:
return
_bfill(
f=self.data.field * self.data.fmult,
x=self.data.x,
y=self.data.y,
clevs=self.data.levels,
bound=0,
alpha=alpha,
fast=fast,
zorder=zorder,
)
def render_lines(
self,
colors: Any,
linewidths: Any,
linestyles: Any,
line_labels: bool,
zero_thick: bool | int,
zorder: int = 1,
) -> None:
"""Render contour lines on a map with Cartopy transform."""
if self.data.x is None or self.data.y is None or self.data.levels is None:
return
if self.data.irregular:
field, lons, lats = _window_irregular_map_data(
self.data.field * self.data.fmult,
self.data.x,
self.data.y,
)
runtime = plotvars.runtime
dec = plotvars.decoration
cs = runtime.mymap.tricontour(
lons,
lats,
field,
self.data.levels,
colors=colors,
linewidths=linewidths,
linestyles=linestyles,
alpha=1.0,
transform=ccrs.PlateCarree(),
zorder=zorder,
)
if hasattr(cs, "collections"):
self.frame_artists.extend(list(cs.collections))
if line_labels and not isinstance(self.data.levels, int):
nd = utility.ndecs(self.data.levels)
fmt = "%d"
if nd != 0:
fmt = "%1." + str(nd) + "f"
runtime.plot.clabel(
cs,
levels=self.data.levels,
fmt=fmt,
colors=colors,
fontsize=dec.text_fontsize,
zorder=zorder,
)
return
runtime = plotvars.runtime
dec = plotvars.decoration
cs = runtime.mymap.contour(
self.data.x,
self.data.y,
self.data.field * self.data.fmult,
self.data.levels,
colors=colors,
linewidths=linewidths,
linestyles=linestyles,
alpha=1.0,
transform=ccrs.PlateCarree(),
zorder=zorder,
)
if hasattr(cs, "collections"):
self.frame_artists.extend(list(cs.collections))
if line_labels and not isinstance(self.data.levels, int):
nd = utility.ndecs(self.data.levels)
fmt = "%d"
if nd != 0:
fmt = "%1." + str(nd) + "f"
runtime.plot.clabel(
cs,
levels=self.data.levels,
fmt=fmt,
colors=colors,
fontsize=dec.text_fontsize,
zorder=zorder,
)
if zero_thick:
cs0 = runtime.mymap.contour(
self.data.x,
self.data.y,
self.data.field * self.data.fmult,
[-1e-32, 0],
colors=colors,
linewidths=zero_thick,
linestyles=linestyles,
alpha=1.0,
transform=ccrs.PlateCarree(),
zorder=zorder,
)
if hasattr(cs0, "collections"):
self.frame_artists.extend(list(cs0.collections))
def render_colorbar(
self,
orientation: str | None,
shrink: float | None,
position: list[float] | None,
fraction: float | None,
thick: float | None,
anchor: float | None,
fontsize: int | None,
fontweight: str | None,
text_up_down: bool,
text_down_up: bool,
drawedges: bool,
labels: list[str] | None = None,
title: str | None = None,
) -> Any:
"""Render colorbar for map contour plots."""
if self.data.levels is None:
return None
return cbar(
labels=labels,
orientation=orientation,
position=position,
shrink=shrink,
title=title or self.data.colorbar_title,
fontsize=fontsize,
fontweight=fontweight,
text_up_down=text_up_down,
text_down_up=text_down_up,
drawedges=drawedges,
fraction=fraction,
thick=thick,
levs=self.data.levels,
anchor=anchor,
)
class XYContourRenderer(ContourRenderer):
"""Cartesian renderer specialization for non-map contour plots.
Handles ptypes 0, 2-7 (simple XY, lat-height, lon-height, Hovmuller, rotated).
"""
def render_filled(
self, alpha: float, zorder: int, transform_first: bool | None
) -> None:
"""Render filled contours in Cartesian space."""
_ = transform_first
if self.data.x is None or self.data.y is None or self.data.levels is None:
return
cmap = self.cs.get_cmap()
runtime = plotvars.runtime
scale = plotvars.scale
runtime.image = runtime.plot.contourf(
self.data.x,
self.data.y,
self.data.field * self.data.fmult,
self.data.levels,
extend=scale.levels_extend,
cmap=cmap,
norm=scale.norm,
alpha=alpha,
zorder=zorder,
)
def render_blockfill(
self, fast: bool | None, alpha: float, zorder: int
) -> None:
"""Render block-filled contours in Cartesian space."""
if self.data.x is None or self.data.y is None or self.data.levels is None:
return
_bfill(
f=self.data.field * self.data.fmult,
x=self.data.x,
y=self.data.y,
clevs=self.data.levels,
bound=0,
alpha=alpha,
fast=fast,
zorder=zorder,
)
def render_lines(
self,
colors: Any,
linewidths: Any,
linestyles: Any,
line_labels: bool,
zero_thick: bool | int,
zorder: int = 1,
) -> None:
"""Render contour lines in Cartesian space."""
if self.data.x is None or self.data.y is None or self.data.levels is None:
return
runtime = plotvars.runtime
dec = plotvars.decoration
cs = runtime.plot.contour(
self.data.x,
self.data.y,
self.data.field * self.data.fmult,
self.data.levels,
colors=colors,
linewidths=linewidths,
linestyles=linestyles,
zorder=zorder,
)
if line_labels and not isinstance(self.data.levels, int):
nd = utility.ndecs(self.data.levels)
fmt = "%d"
if nd != 0:
fmt = "%1." + str(nd) + "f"
runtime.plot.clabel(
cs,
fmt=fmt,
colors=colors,
fontsize=dec.text_fontsize,
zorder=zorder,
)
if zero_thick:
runtime.plot.contour(
self.data.x,
self.data.y,
self.data.field * self.data.fmult,
[-1e-32, 0],
colors=colors,
linewidths=zero_thick,
linestyles=linestyles,
alpha=1.0,
zorder=zorder,
)
def render_colorbar(
self,
orientation: str | None,
shrink: float | None,
position: list[float] | None,
fraction: float | None,
thick: float | None,
anchor: float | None,
fontsize: int | None,
fontweight: str | None,
text_up_down: bool,
text_down_up: bool,
drawedges: bool,
labels: list[str] | None = None,
title: str | None = None,
) -> Any:
"""Render colorbar for Cartesian contour plots."""
if self.data.levels is None:
return None
return cbar(
labels=labels,
orientation=orientation,
position=position,
shrink=shrink,
title=title or self.data.colorbar_title,
fontsize=fontsize,
fontweight=fontweight,
text_up_down=text_up_down,
text_down_up=text_down_up,
drawedges=drawedges,
fraction=fraction,
thick=thick,
levs=self.data.levels,
anchor=anchor,
)
def levs(min=None, max=None, step=None, manual=None, extend="both"):
"""Set or clear the contour levels stored in shared plotting state."""
scale = plotvars.scale
runtime = plotvars.runtime
if all(val is not None for val in [min, max]) and step is None:
print(
"\ncfp.levs error: when the min and max are specified "
"a step also needs to be specified\n"
)
return
if all(val is None for val in [min, max, step, manual]):
scale.levels = None
scale.levels_min = None
scale.levels_max = None
scale.levels_step = None
scale.levels_extend = "both"
scale.norm = None
runtime.user_levs = 0
return
if manual is not None:
scale.levels = np.array(manual)
scale.levels_min = None
scale.levels_max = None
scale.levels_step = None
ncolors = np.size(scale.levels)
if extend == "both" or extend == "max":
ncolors = ncolors - 1
scale.norm = matplotlib.colors.BoundaryNorm(
boundaries=scale.levels, ncolors=ncolors
)
runtime.user_levs = 1
else:
if all(val is not None for val in [min, max, step]):
scale.levels_min = min
scale.levels_max = max
scale.levels_step = step
scale.norm = None
if all(isinstance(item, int) for item in [min, max, step]):
lstep = step * 1e-10
levs_arr = np.arange(min, max + lstep, step, dtype=np.float64)
levs_arr = ((levs_arr * 1e10).astype(np.int64)).astype(np.float64)
levs_arr = (levs_arr / 1e10).astype(np.int64)
scale.levels = levs_arr
else:
lstep = step * 1e-10
levs_arr = np.arange(min, max + lstep, step, dtype=np.float64)
levs_arr = (levs_arr * 1e10).astype(np.int64).astype(np.float64)
levs_arr = levs_arr / 1e10
scale.levels = levs_arr
runtime.user_levs = 1
for pt in np.arange(np.size(scale.levels)):
ndecs = str(scale.levels[pt])[::-1].find(".")
if ndecs > 7:
scale.levels[pt] = round(scale.levels[pt], 7)
if step is not None and all(val is None for val in [min, max]):