-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathscalebar.py
901 lines (724 loc) · 28.5 KB
/
scalebar.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
"""
Artist for matplotlib to display a scale / micron bar.
Example::
>>> fig = plt.figure()
>>> ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
>>> ax.imshow(...)
>>> scalebar = ScaleBar(0.2)
>>> ax.add_artist(scalebar)
>>> plt.show()
The following parameters are available for customization in the matplotlibrc:
- scalebar.length_fraction
- scalebar.height_fraction
- scalebar.location
- scalebar.pad
- scalebar.border_pad
- scalebar.sep
- scalebar.frameon
- scalebar.color
- scalebar.box_color
- scalebar.box_alpha
- scalebar.scale_loc
- scalebar.label_loc
See the class documentation (:class:`.Scalebar`) for a description of the
parameters.
"""
__all__ = [
"ScaleBar",
"SI_LENGTH",
"SI_LENGTH_RECIPROCAL",
"IMPERIAL_LENGTH",
"ASTRO_LENGTH",
"PIXEL_LENGTH",
"ATOMIC_LENGTH",
"ATOMIC_LENGTH_RECIPROCAL",
]
# Standard library modules.
import bisect
import warnings
import dataclasses
# Third party modules.
import matplotlib
from matplotlib.artist import Artist
from matplotlib.font_manager import FontProperties
from matplotlib.rcsetup import (
defaultParams,
validate_float,
validate_bool,
validate_color,
ValidateInStrings,
)
from matplotlib.offsetbox import (
AuxTransformBox,
TextArea,
VPacker,
HPacker,
AnchoredOffsetbox,
)
from matplotlib.patches import Rectangle
# Local modules.
from matplotlib_scalebar.dimension import (
_Dimension,
SILengthDimension,
SILengthReciprocalDimension,
ImperialLengthDimension,
AstronomicalLengthDimension,
PixelLengthDimension,
AngleDimension,
AtomicLengthDimension,
AtomicLengthReciprocalDimension,
)
# Globals and constants variables.
# Setup of extra parameters in the matplotlic rc
_VALID_SCALE_LOCATIONS = ["bottom", "top", "right", "left", "none"]
_validate_scale_loc = ValidateInStrings(
"scale_loc", _VALID_SCALE_LOCATIONS, ignorecase=True
)
_VALID_LABEL_LOCATIONS = ["bottom", "top", "right", "left", "none"]
_validate_label_loc = ValidateInStrings(
"label_loc", _VALID_LABEL_LOCATIONS, ignorecase=True
)
_VALID_ROTATIONS = ["horizontal", "horizontal-only", "vertical", "vertical-only"]
_validate_rotation = ValidateInStrings("rotation", _VALID_ROTATIONS, ignorecase=True)
def _validate_legend_loc(loc):
rc = matplotlib.RcParams()
rc["legend.loc"] = loc
return loc
defaultParams.update(
{
"scalebar.length_fraction": [0.2, validate_float],
"scalebar.width_fraction": [0.01, validate_float],
"scalebar.location": ["upper right", _validate_legend_loc],
"scalebar.pad": [0.2, validate_float],
"scalebar.border_pad": [0.1, validate_float],
"scalebar.sep": [5, validate_float],
"scalebar.frameon": [True, validate_bool],
"scalebar.color": ["k", validate_color],
"scalebar.box_color": ["w", validate_color],
"scalebar.box_alpha": [1.0, validate_float],
"scalebar.scale_loc": ["bottom", _validate_scale_loc],
"scalebar.label_loc": ["top", _validate_label_loc],
"scalebar.rotation": ["horizontal", _validate_rotation],
}
)
_all_deprecated = getattr(matplotlib, "_all_deprecated", {})
# Recreate the validate function
matplotlib.rcParams.validate = dict(
(key, converter)
for key, (default, converter) in defaultParams.items()
if key not in _all_deprecated
)
# Dimension lookup
SI_LENGTH = "si-length"
SI_LENGTH_RECIPROCAL = "si-length-reciprocal"
IMPERIAL_LENGTH = "imperial-length"
ASTRO_LENGTH = "astro-length"
PIXEL_LENGTH = "pixel-length"
ANGLE = "angle"
ATOMIC_LENGTH = "atomic-length"
ATOMIC_LENGTH_RECIPROCAL = "atomic-length-reciprocal"
_DIMENSION_LOOKUP = {
SI_LENGTH: SILengthDimension,
SI_LENGTH_RECIPROCAL: SILengthReciprocalDimension,
IMPERIAL_LENGTH: ImperialLengthDimension,
ASTRO_LENGTH: AstronomicalLengthDimension,
PIXEL_LENGTH: PixelLengthDimension,
ANGLE: AngleDimension,
ATOMIC_LENGTH: AtomicLengthDimension,
ATOMIC_LENGTH_RECIPROCAL: AtomicLengthReciprocalDimension,
}
@dataclasses.dataclass
class ScaleBarInfo:
length_px: int
value: float
units: str
scale_text: str
window_extent: matplotlib.transforms.Bbox
class ScaleBar(Artist):
zorder = 6
_PREFERRED_VALUES = [1, 2, 5, 10, 15, 20, 25, 50, 75, 100, 125, 150, 200, 500, 750]
_LOCATIONS = {
"upper right": 1,
"upper left": 2,
"lower left": 3,
"lower right": 4,
"right": 5,
"center left": 6,
"center right": 7,
"lower center": 8,
"upper center": 9,
"center": 10,
}
def __init__(
self,
dx,
units="m",
dimension="si-length",
label=None,
length_fraction=None,
height_fraction=None,
width_fraction=None,
location=None,
loc=None,
pad=None,
border_pad=None,
sep=None,
frameon=None,
color=None,
box_color=None,
box_alpha=None,
scale_loc=None,
label_loc=None,
font_properties=None,
label_formatter=None,
scale_formatter=None,
fixed_value=None,
fixed_units=None,
animated=False,
rotation=None,
bbox_to_anchor=None,
bbox_transform=None,
):
"""
Creates a new scale bar.
There are two modes of operation:
1. Length, value and units of the scale bar are automatically
determined based on the specified pixel size *dx* and
*length_fraction*. The value will only take the following numbers:
1, 2, 5, 10, 15, 20, 25, 50, 75, 100, 125, 150, 200, 500 or 750.
2. The desired value and units are specified by the user
(*fixed_value* and *fixed_units*) and the length is calculated
based on the specified pixel size *dx*.
:arg dx: size of one pixel in *units*
Set ``dx`` to 1.0 if the axes image has already been calibrated by
setting its ``extent``.
:type dx: :class:`float`
:arg units: units of *dx* (default: ``m``)
:type units: :class:`str`
:arg dimension: dimension of *dx* and *units*.
It can either be equal
* ``:const:`si-length```: scale bar showing km, m, cm, etc.
* ``:const:`imperial-length```: scale bar showing in, ft, yd, mi, etc.
* ``:const:`si-length-reciprocal```: scale bar showing 1/m, 1/cm, etc.
* ``:const:`astro-length```: scale bar showing pc, kpc ly, AU, etc.
* ``:const:`pixel-length```: scale bar showing px, kpx, Mpx, etc.
* ``:const:`angle```: scale bar showing \u00b0, \u2032 or \u2032\u2032.
* ``:const:`atomic-length```: scale bar showing \AA, nm, \u00B5m, etc.
* ``:const:`atomic-length-reciprocal```: scale bar showing 1/\AA, 1/nm, 1/\u00B5m, etc.
* a :class:`matplotlib_scalebar.dimension._Dimension` object
:type dimension: :class:`str` or
:class:`matplotlib_scalebar.dimension._Dimension`
:arg label: optional label associated with the scale bar
(default: ``None``, no label is shown)
:type label: :class:`str`
:arg length_fraction: length of the scale bar as a fraction of the
axes's width (default: rcParams['scalebar.lenght_fraction'] or ``0.2``).
This argument is ignored if a *fixed_value* is specified.
:type length_fraction: :class:`float`
:arg width_fraction: width of the scale bar as a fraction of the
axes's height (default: rcParams['scalebar.width_fraction'] or ``0.01``)
:type width_fraction: :class:`float`
:arg location: a location code (same as legend)
(default: rcParams['scalebar.location'] or ``upper right``)
:type location: :class:`str`
:arg loc: alias for location
:type loc: :class:`str`
:arg pad: fraction of the font size
(default: rcParams['scalebar.pad'] or ``0.2``)
:type pad: :class:`float`
:arg border_pad : fraction of the font size
(default: rcParams['scalebar.border_pad'] or ``0.1``)
:type border_pad: :class:`float`
:arg sep : separation between scale bar and label in points
(default: rcParams['scalebar.sep'] or ``5``)
:type sep: :class:`float`
:arg frameon : if True, will draw a box around the scale bar
and label (default: rcParams['scalebar.frameon'] or ``True``)
:type frameon: :class:`bool`
:arg color : color for the scale bar and label
(default: rcParams['scalebar.color'] or ``k``)
:type color: :class:`str`
:arg box_color: color of the box (if *frameon*)
(default: rcParams['scalebar.box_color'] or ``w``)
:type box_color: :class:`str`
:arg box_alpha: transparency of box
(default: rcParams['scalebar.box_alpha'] or ``1.0``)
:type box_alpha: :class:`float`
:arg scale_loc : either ``bottom``, ``top``, ``left``, ``right``, ``none``
(default: rcParams['scalebar.scale_loc'] or ``bottom``).
If ``none`` the scale is not shown.
:type scale_loc: :class:`str`
:arg label_loc: either ``bottom``, ``top``, ``left``, ``right``, ``none``
(default: rcParams['scalebar.label_loc'] or ``top``).
If ``none`` the label is not shown.
:type label_loc: :class:`str`
:arg font_properties: font properties of the label text, specified
either as dict or `fontconfig <http://www.fontconfig.org/>`_
pattern (XML).
:type font_properties: :class:`matplotlib.font_manager.FontProperties`,
:class:`str` or :class:`dict`
:arg scale_formatter: function used to format the label. Needs to take
the value (float) and the unit (str) as input and return the label
string.
:type scale_formatter: :class:`func`
:arg fixed_value: value for the scale bar. If ``None``, the value is
automatically determined based on *length_fraction*.
:type fixed_value: :class:`float`
:arg fixed_units: units of the *fixed_value*. If ``None`` and
*fixed_value* is not ``None``, the units of *dx* are used.
:type fixed_units: :class:`str`
:arg animated: animation state (default: ``False``)
:type animated: :class`bool`
:arg rotation: ``horizontal``, ``vertical``, ``horizontal-only``,
or ``vertical-only``
(default: rcParams['scalebar.rotation'] or ``horizontal``).
By default, ScaleBar checks that it is getting drawn on an axes
with equal aspect ratio and emits a warning if this is not the case.
The -only variants suppress that check.
:type rotation: :class:`str`
:arg bbox_to_anchor: box that is used to position the scalebar
in conjunction with location. If ``None`` the figure bbox is used.
:type bbox_to_anchor: :class:`BboxBase`, `2-tuple`, or `4-tuple` of floats
:arg bbox_transform: transform for the bounding box
:type bbox_transform: :class:`matplotlib.transforms.Transform`
"""
Artist.__init__(self)
# Deprecation
if height_fraction is not None:
warnings.warn(
"The height_fraction argument was deprecated. "
"Use width_fraction instead.",
DeprecationWarning,
)
width_fraction = width_fraction or height_fraction
if label_formatter is not None:
warnings.warn(
"The label_formatter argument was deprecated. "
"Use scale_formatter instead.",
DeprecationWarning,
)
scale_formatter = scale_formatter or label_formatter
if (
loc is not None
and location is not None
and self._convert_location(loc) != self._convert_location(location)
):
raise ValueError("loc and location are specified and not equal")
self.dx = dx
self.dimension = dimension # Should be initialize before units
self.units = units
self.label = label
self.length_fraction = length_fraction
self.width_fraction = width_fraction
self.location = location or loc
self.pad = pad
self.border_pad = border_pad
self.sep = sep
self.frameon = frameon
self.color = color
self.box_color = box_color
self.box_alpha = box_alpha
self.scale_loc = scale_loc
self.label_loc = label_loc
self.scale_formatter = scale_formatter
self.font_properties = font_properties
self.fixed_value = fixed_value
self.fixed_units = fixed_units
self.set_animated(animated)
self.rotation = rotation
self.bbox_to_anchor = bbox_to_anchor
self.bbox_transform = bbox_transform
self._info = None
def _calculate_best_length(self, length_px):
dx = self.dx
units = self.units
value = length_px * dx
newvalue, newunits = self.dimension.calculate_preferred(value, units)
factor = value / newvalue
index = bisect.bisect_left(self._PREFERRED_VALUES, newvalue)
if index > 0:
# When we get the lowest index of the list, removing -1 will
# return the last index.
index -= 1
newvalue = self._PREFERRED_VALUES[index]
length_px = newvalue * factor / dx
return length_px, newvalue, newunits
def _calculate_exact_length(self, value, units):
newvalue = self.dimension.convert(value, units, self.units)
return newvalue / self.dx
def draw(self, renderer, *args, **kwargs):
self._info = None
if not self.get_visible():
return
if self.dx == 0:
return
# Late import
from matplotlib import rcParams
# Deprecation
if rcParams.get("scalebar.height_fraction") is not None:
warnings.warn(
"The scalebar.height_fraction parameter in matplotlibrc is deprecated. "
"Use scalebar.width_fraction instead.",
DeprecationWarning,
)
rcParams.setdefault(
"scalebar.width_fraction", rcParams["scalebar.height_fraction"]
)
# Get parameters
def _get_value(attr, default):
value = getattr(self, attr)
if value is None:
value = rcParams.get("scalebar." + attr, default)
return value
length_fraction = _get_value("length_fraction", 0.2)
width_fraction = _get_value("width_fraction", 0.01)
location = _get_value("location", "upper right")
if isinstance(location, str):
location = self._LOCATIONS[location.lower()]
pad = _get_value("pad", 0.2)
border_pad = _get_value("border_pad", 0.1)
sep = _get_value("sep", 5)
frameon = _get_value("frameon", True)
color = _get_value("color", "k")
box_color = _get_value("box_color", "w")
box_alpha = _get_value("box_alpha", 1.0)
scale_loc = _get_value("scale_loc", "bottom").lower()
label_loc = _get_value("label_loc", "top").lower()
font_properties = self.font_properties
fixed_value = self.fixed_value
fixed_units = self.fixed_units or self.units
rotation = _get_value("rotation", "horizontal").lower()
if rotation.endswith("-only"):
rotation = rotation[:-5]
else: # Check aspect ratio.
if self.axes.get_aspect() != 1:
warnings.warn(
f"Drawing scalebar on axes with unequal aspect ratio; "
f"either call ax.set_aspect(1) or suppress the warning with "
f"rotation='{rotation}-only'."
)
label = self.label
# Create text properties
textprops = {"color": color, "rotation": rotation}
if font_properties is not None:
textprops["fontproperties"] = font_properties
# Calculate value, units and length
ax = self.axes
xlim = ax.get_xlim()
ylim = ax.get_ylim()
if rotation == "vertical":
xlim, ylim = ylim, xlim
# Mode 1: Auto
if self.fixed_value is None:
length_px = abs(xlim[1] - xlim[0]) * length_fraction
length_px, value, units = self._calculate_best_length(length_px)
# Mode 2: Fixed
else:
value = fixed_value
units = fixed_units
length_px = self._calculate_exact_length(value, units)
scale_text = self.scale_formatter(value, self.dimension.to_latex(units))
width_px = abs(ylim[1] - ylim[0]) * width_fraction
# Create scale bar
if rotation == "horizontal":
scale_rect = Rectangle(
(0, 0),
length_px,
width_px,
fill=True,
facecolor=color,
edgecolor="none",
)
else:
scale_rect = Rectangle(
(0, 0),
width_px,
length_px,
fill=True,
facecolor=color,
edgecolor="none",
)
scale_bar_box = AuxTransformBox(ax.transData)
scale_bar_box.add_artist(scale_rect)
# Create scale text
if scale_loc != "none":
scale_text_box = TextArea(scale_text, textprops=textprops)
if scale_loc in ["bottom", "right"]:
children = [scale_bar_box, scale_text_box]
else:
children = [scale_text_box, scale_bar_box]
if scale_loc in ["bottom", "top"]:
Packer = VPacker
else:
Packer = HPacker
scale_box = Packer(children=children, align="center", pad=0, sep=sep)
else:
scale_box = scale_bar_box
# Create label
if label and label_loc != "none":
label_box = TextArea(label, textprops=textprops)
else:
label_box = None
# Create final offset box
if label_box:
if label_loc in ["bottom", "right"]:
children = [scale_box, label_box]
else:
children = [label_box, scale_box]
if label_loc in ["bottom", "top"]:
Packer = VPacker
else:
Packer = HPacker
child = Packer(children=children, align="center", pad=0, sep=sep)
else:
child = scale_box
box = AnchoredOffsetbox(
loc=location,
pad=pad,
child=child,
borderpad=border_pad,
frameon=frameon,
bbox_to_anchor=self.bbox_to_anchor,
bbox_transform=self.bbox_transform,
)
box.axes = ax
box.set_figure(self.get_figure())
box.patch.set_color(box_color)
box.patch.set_alpha(box_alpha)
box.draw(renderer)
self._info = ScaleBarInfo(
length_px, value, units, scale_text, box.get_window_extent(renderer)
)
def get_dx(self):
return self._dx
def set_dx(self, dx):
self._dx = float(dx)
dx = property(get_dx, set_dx)
def get_dimension(self):
return self._dimension
def set_dimension(self, dimension):
if dimension in _DIMENSION_LOOKUP:
dimension = _DIMENSION_LOOKUP[dimension]()
if not isinstance(dimension, _Dimension):
raise ValueError(
f"Unknown dimension: {dimension}. "
f"Known dimensions: {', '.join(_DIMENSION_LOOKUP)}"
)
self._dimension = dimension
dimension = property(get_dimension, set_dimension)
def get_units(self):
return self._units
def set_units(self, units):
"""
Set the units of the scale bar.
"""
old_units = self._units if hasattr(self, '_units') else None
old_dx = self._dx if hasattr(self, '_dx') else None
# Auto-detect Angstrom units and switch to atomic dimension
if units in ["Å", "A", "angstrom"]:
self._dimension = _DIMENSION_LOOKUP[ATOMIC_LENGTH]()
elif units in ["1/Å", "1/A", "1/angstrom"]:
self._dimension = _DIMENSION_LOOKUP[ATOMIC_LENGTH_RECIPROCAL]()
elif hasattr(self, '_dimension') and isinstance(self._dimension, (AtomicLengthDimension, AtomicLengthReciprocalDimension)) and units not in ["Å", "A", "angstrom", "1/Å", "1/A", "1/angstrom"]:
# Switch back to SI if changing from Angstrom to non-Angstrom units
if '/' in units:
self._dimension = _DIMENSION_LOOKUP[SI_LENGTH_RECIPROCAL]()
else:
self._dimension = _DIMENSION_LOOKUP[SI_LENGTH]()
if not self.dimension.is_valid_units(units):
raise ValueError(f"Invalid unit ({units}) with dimension")
# Convert dx to the new units if we're changing units
if old_units is not None and old_dx is not None:
# All conversions are now handled by the dimension's convert method
# since factors are relative to meters
self._dx = self.dimension.convert(old_dx, old_units, units)
self._units = units
units = property(get_units, set_units)
def get_label(self):
return self._label
def set_label(self, label):
self._label = label
label = property(get_label, set_label)
def get_length_fraction(self):
return self._length_fraction
def set_length_fraction(self, fraction):
if fraction is not None:
fraction = float(fraction)
if fraction <= 0.0 or fraction > 1.0:
raise ValueError("Length fraction must be between [0.0, 1.0]")
self._length_fraction = fraction
length_fraction = property(get_length_fraction, set_length_fraction)
def get_width_fraction(self):
return self._width_fraction
def set_width_fraction(self, fraction):
if fraction is not None:
fraction = float(fraction)
if fraction <= 0.0 or fraction > 1.0:
raise ValueError("Width fraction must be between [0.0, 1.0]")
self._width_fraction = fraction
width_fraction = property(get_width_fraction, set_width_fraction)
def get_height_fraction(self):
warnings.warn(
"The get_height_fraction method is deprecated. "
"Use get_width_fraction instead.",
DeprecationWarning,
)
return self.width_fraction
def set_height_fraction(self, fraction):
warnings.warn(
"The set_height_fraction method is deprecated. "
"Use set_width_fraction instead.",
DeprecationWarning,
)
self.width_fraction = fraction
height_fraction = property(get_height_fraction, set_height_fraction)
@classmethod
def _convert_location(cls, loc):
if isinstance(loc, str):
if loc not in cls._LOCATIONS:
raise ValueError(
f"Unknown location: {loc}. "
f"Valid locations: {', '.join(cls._LOCATIONS)}"
)
loc = cls._LOCATIONS[loc]
return loc
def get_location(self):
return self._location
def set_location(self, loc):
self._location = self._convert_location(loc)
location = property(get_location, set_location)
get_loc = get_location
set_loc = set_location
loc = location
def get_pad(self):
return self._pad
def set_pad(self, pad):
self._pad = pad
pad = property(get_pad, set_pad)
def get_border_pad(self):
return self._border_pad
def set_border_pad(self, pad):
self._border_pad = pad
border_pad = property(get_border_pad, set_border_pad)
def get_sep(self):
return self._sep
def set_sep(self, sep):
self._sep = sep
sep = property(get_sep, set_sep)
def get_frameon(self):
return self._frameon
def set_frameon(self, on):
self._frameon = on
frameon = property(get_frameon, set_frameon)
def get_color(self):
return self._color
def set_color(self, color):
self._color = color
color = property(get_color, set_color)
def get_box_color(self):
return self._box_color
def set_box_color(self, color):
self._box_color = color
box_color = property(get_box_color, set_box_color)
def get_box_alpha(self):
return self._box_alpha
def set_box_alpha(self, alpha):
if alpha is not None:
alpha = float(alpha)
if alpha < 0.0 or alpha > 1.0:
raise ValueError("Alpha must be between [0.0, 1.0]")
self._box_alpha = alpha
box_alpha = property(get_box_alpha, set_box_alpha)
def get_scale_loc(self):
return self._scale_loc
def set_scale_loc(self, loc):
if loc is not None and loc not in _VALID_SCALE_LOCATIONS:
raise ValueError(
f"Unknown location: {loc}. "
f"Valid locations: {', '.join(_VALID_SCALE_LOCATIONS)}"
)
self._scale_loc = loc
scale_loc = property(get_scale_loc, set_scale_loc)
def get_label_loc(self):
return self._label_loc
def set_label_loc(self, loc):
if loc is not None and loc not in _VALID_LABEL_LOCATIONS:
raise ValueError(
f"Unknown location: {loc}. "
f"Valid locations: {', '.join(_VALID_LABEL_LOCATIONS)}"
)
self._label_loc = loc
label_loc = property(get_label_loc, set_label_loc)
def get_font_properties(self):
return self._font_properties
def set_font_properties(self, props):
if props is None:
props = FontProperties()
elif isinstance(props, dict):
props = FontProperties(**props)
elif isinstance(props, str):
props = FontProperties(props)
else:
raise ValueError(
"Unsupported `font_properties`. "
"Pass either a dict or a font config pattern as string."
)
self._font_properties = props
font_properties = property(get_font_properties, set_font_properties)
def get_scale_formatter(self):
if self._scale_formatter is None:
return self.dimension.create_label
return self._scale_formatter
def set_scale_formatter(self, scale_formatter):
self._scale_formatter = scale_formatter
scale_formatter = property(get_scale_formatter, set_scale_formatter)
def get_label_formatter(self):
warnings.warn(
"The get_label_formatter method is deprecated. "
"Use get_scale_formatter instead.",
DeprecationWarning,
)
return self.scale_formatter
def set_label_formatter(self, scale_formatter):
warnings.warn(
"The set_label_formatter method is deprecated. "
"Use set_scale_formatter instead.",
DeprecationWarning,
)
self.scale_formatter = scale_formatter
label_formatter = property(get_label_formatter, set_label_formatter)
def get_fixed_value(self):
return self._fixed_value
def set_fixed_value(self, value):
self._fixed_value = value
fixed_value = property(get_fixed_value, set_fixed_value)
def get_fixed_units(self):
return self._fixed_units
def set_fixed_units(self, units):
self._fixed_units = units
fixed_units = property(get_fixed_units, set_fixed_units)
def get_rotation(self):
return self._rotation
def set_rotation(self, rotation):
if rotation is not None and rotation not in _VALID_ROTATIONS:
raise ValueError(
f"Unknown rotation: {rotation}. "
f"Valid locations: {', '.join(_VALID_ROTATIONS)}"
)
self._rotation = rotation
rotation = property(get_rotation, set_rotation)
def get_bbox_to_anchor(self):
return self._bbox_to_anchor
def set_bbox_to_anchor(self, bbox_to_anchor):
self._bbox_to_anchor = bbox_to_anchor
bbox_to_anchor = property(get_bbox_to_anchor, set_bbox_to_anchor)
def get_bbox_transform(self):
return self._bbox_transform
def set_bbox_transform(self, bbox_transform):
self._bbox_transform = bbox_transform
bbox_transform = property(get_bbox_transform, set_bbox_transform)
@property
def info(self):
if self._info is None:
raise ValueError("Scale bar has not been drawn. Call figure.canvas.draw()")
return self._info