FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
matplotlib/lib/matplotlib/rcsetup.py at v3.11.2 · matplotlib/matplotlib · GitHub
matplotlib
/
matplotlib
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
8.5k
Star
23.3k
Code
Issues
1.1k
Pull requests
430
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
rcsetup.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
3429 lines (3180 loc) · 116 KB
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
rcsetup.py
Copy path
File metadata and controls
3429 lines (3180 loc) · 116 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
The rcsetup module contains the validation code for customization using
Matplotlib's rc settings.
Each rc setting is assigned a function used to validate any attempted changes
to that setting. The validation functions are defined in the rcsetup module,
and are used to construct the rcParams global object which stores the settings
and is referenced throughout Matplotlib.
The default values of the rc settings are set in the default matplotlibrc file.
Any additions or deletions to the parameter set listed here should also be
propagated to the :file:`lib/matplotlib/mpl-data/matplotlibrc` in Matplotlib's
root source directory. New rcparams also need to be added to the RcKeyType enum
in :file:`lib/matplotlib/typing.py`.
"""
import
ast
from
dataclasses
import
dataclass
from
functools
import
lru_cache
,
reduce
from
numbers
import
Real
import
operator
import
os
import
re
from
typing
import
Any
from
collections
.
abc
import
Callable
import
numpy
as
np
import
matplotlib
as
mpl
from
matplotlib
import
_api
,
cbook
from
matplotlib
.
backends
import
backend_registry
from
matplotlib
.
cbook
import
ls_mapper
from
matplotlib
.
colors
import
Colormap
,
is_color_like
from
matplotlib
.
_fontconfig_pattern
import
parse_fontconfig_pattern
from
matplotlib
.
_enums
import
JoinStyle
,
CapStyle
# Don't let the original cycler collide with our validating cycler
from
cycler
import
Cycler
,
concat
as
cconcat
,
cycler
as
ccycler
class
ValidateInStrings
:
def
__init__
(
self
,
key
,
valid
,
ignorecase
=
False
,
*
,
_deprecated_since
=
None
):
"""*valid* is a list of legal strings."""
self
.
key
=
key
self
.
ignorecase
=
ignorecase
self
.
_deprecated_since
=
_deprecated_since
def
func
(
s
):
if
ignorecase
:
return
s
.
lower
()
else
:
return
s
self
.
valid
=
{
func
(
k
):
k
for
k
in
valid
}
def
__call__
(
self
,
s
):
if
self
.
_deprecated_since
:
name
,
=
(
k
for
k
,
v
in
globals
().
items
()
if
v
is
self
)
_api
.
warn_deprecated
(
self
.
_deprecated_since
,
name
=
name
,
obj_type
=
"function"
)
if
self
.
ignorecase
and
isinstance
(
s
,
str
):
s
=
s
.
lower
()
if
s
in
self
.
valid
:
return
self
.
valid
[
s
]
msg
=
(
f"
{
s
!r
}
is not a valid value for
{
self
.
key
}
; supported values "
f"are
{
[
*
self
.
valid
.
values
()]
}
"
)
if
(
isinstance
(
s
,
str
)
and
(
s
.
startswith
(
'"'
)
and
s
.
endswith
(
'"'
)
or
s
.
startswith
(
"'"
)
and
s
.
endswith
(
"'"
))
and
s
[
1
:
-
1
]
in
self
.
valid
):
msg
+=
"; remove quotes surrounding your string"
raise
ValueError
(
msg
)
def
__repr__
(
self
):
return
(
f"
{
self
.
__class__
.
__name__
}
("
f"key=
{
self
.
key
!r
}
, valid=
{
[
*
self
.
valid
.
values
()]
}
, "
f"ignorecase=
{
self
.
ignorecase
}
)"
)
def
__eq__
(
self
,
other
):
if
self
is
other
:
return
True
if
not
isinstance
(
other
,
ValidateInStrings
):
return
NotImplemented
return
(
self
.
key
,
self
.
ignorecase
,
self
.
_deprecated_since
,
tuple
(
sorted
(
self
.
valid
.
items
()))
)
==
(
other
.
key
,
other
.
ignorecase
,
other
.
_deprecated_since
,
tuple
(
sorted
(
other
.
valid
.
items
()))
)
def
__hash__
(
self
):
return
hash
((
self
.
key
,
self
.
ignorecase
,
self
.
_deprecated_since
,
tuple
(
sorted
(
self
.
valid
.
items
()))
))
def
_single_string_color_list
(
s
,
scalar_validator
):
"""
Convert the string *s* to a list of colors interpreting it either as a
color sequence name, or a string containing single-letter colors.
"""
try
:
colors
=
mpl
.
color_sequences
[
s
]
except
KeyError
:
try
:
# Sometimes, a list of colors might be a single string
# of single-letter colornames. So give that a shot.
colors
=
[
scalar_validator
(
v
.
strip
())
for
v
in
s
if
v
.
strip
()]
except
ValueError
:
raise
ValueError
(
f'
{
s
!r
}
is neither a color sequence name nor can '
'it be interpreted as a list of colors'
)
return
colors
@
lru_cache
def
_listify_validator
(
scalar_validator
,
allow_stringlist
=
False
,
*
,
n
=
None
,
doc
=
None
):
def
f
(
s
):
if
isinstance
(
s
,
str
):
try
:
val
=
[
scalar_validator
(
v
.
strip
())
for
v
in
s
.
split
(
','
)
if
v
.
strip
()]
except
Exception
:
if
allow_stringlist
:
# Special handling for colors
val
=
_single_string_color_list
(
s
,
scalar_validator
)
else
:
raise
# Allow any ordered sequence type -- generators, np.ndarray, pd.Series
# -- but not sets, whose iteration order is non-deterministic.
elif
np
.
iterable
(
s
)
and
not
isinstance
(
s
, (
set
,
frozenset
)):
# The condition on this list comprehension will preserve the
# behavior of filtering out any empty strings (behavior was
# from the original validate_stringlist()), while allowing
# any non-string/text scalar values such as numbers and arrays.
val
=
[
scalar_validator
(
v
)
for
v
in
s
if
not
isinstance
(
v
,
str
)
or
v
]
else
:
raise
ValueError
(
f"Expected str or other non-set iterable, but got
{
s
}
"
)
if
n
is
not
None
and
len
(
val
)
!=
n
:
raise
ValueError
(
f"Expected
{
n
}
values, but there are
{
len
(
val
)
}
values in
{
s
}
"
)
return
val
try
:
f
.
__name__
=
f"
{
scalar_validator
.
__name__
}
list"
except
AttributeError
:
# class instance.
f
.
__name__
=
f"
{
type
(
scalar_validator
).
__name__
}
List"
f
.
__qualname__
=
f
.
__qualname__
.
rsplit
(
"."
,
1
)[
0
]
+
"."
+
f
.
__name__
f
.
__doc__
=
doc
if
doc
is
not
None
else
scalar_validator
.
__doc__
return
f
def
validate_any
(
s
):
return
s
validate_anylist
=
_listify_validator
(
validate_any
)
def
_validate_date
(
s
):
try
:
np
.
datetime64
(
s
)
return
s
except
ValueError
:
raise
ValueError
(
f'
{
s
!r
}
should be a string that can be parsed by numpy.datetime64'
)
def
validate_bool
(
b
):
"""Convert b to ``bool`` or raise."""
if
isinstance
(
b
,
str
):
b
=
b
.
lower
()
if
b
in
(
't'
,
'y'
,
'yes'
,
'on'
,
'true'
,
'1'
,
1
,
True
):
return
True
elif
b
in
(
'f'
,
'n'
,
'no'
,
'off'
,
'false'
,
'0'
,
0
,
False
):
return
False
else
:
raise
ValueError
(
f'Cannot convert
{
b
!r
}
to bool'
)
def
validate_axisbelow
(
s
):
try
:
return
validate_bool
(
s
)
except
ValueError
:
if
isinstance
(
s
,
str
):
if
s
==
'line'
:
return
'line'
raise
ValueError
(
f'
{
s
!r
}
cannot be interpreted as'
' True, False, or "line"'
)
def
validate_dpi
(
s
):
"""Confirm s is string 'figure' or convert s to float or raise."""
if
s
==
'figure'
:
return
s
try
:
return
float
(
s
)
except
ValueError
as
e
:
raise
ValueError
(
f'
{
s
!r
}
is not string "figure" and '
f'could not convert
{
s
!r
}
to float'
)
from
e
def
_make_type_validator
(
cls
,
*
,
allow_none
=
False
):
"""
Return a validator that converts inputs to *cls* or raises (and possibly
allows ``None`` as well).
"""
def
validator
(
s
):
if
(
allow_none
and
(
s
is
None
or
cbook
.
_str_lower_equal
(
s
,
"none"
))):
if
cbook
.
_str_lower_equal
(
s
,
"none"
)
and
s
!=
"None"
:
_api
.
warn_deprecated
(
"3.11"
,
message
=
f"Using the capitalization
{
s
!r
}
in matplotlibrc for "
"*None* is deprecated in %(removal)s and will lead to an "
"error from version 3.13 onward. Please use 'None' "
"instead."
)
return
None
if
cls
is
str
and
not
isinstance
(
s
,
str
):
raise
ValueError
(
f'Could not convert
{
s
!r
}
to str'
)
try
:
return
cls
(
s
)
except
(
TypeError
,
ValueError
)
as
e
:
raise
ValueError
(
f'Could not convert
{
s
!r
}
to
{
cls
.
__name__
}
'
)
from
e
validator
.
__name__
=
f"validate_
{
cls
.
__name__
}
"
if
allow_none
:
validator
.
__name__
+=
"_or_None"
validator
.
__qualname__
=
(
validator
.
__qualname__
.
rsplit
(
"."
,
1
)[
0
]
+
"."
+
validator
.
__name__
)
return
validator
validate_string
=
_make_type_validator
(
str
)
validate_string_or_None
=
_make_type_validator
(
str
,
allow_none
=
True
)
validate_stringlist
=
_listify_validator
(
validate_string
,
doc
=
'return a list of strings'
)
validate_int
=
_make_type_validator
(
int
)
validate_int_or_None
=
_make_type_validator
(
int
,
allow_none
=
True
)
validate_intlist
=
_listify_validator
(
validate_int
,
n
=
2
)
validate_float
=
_make_type_validator
(
float
)
validate_float_or_None
=
_make_type_validator
(
float
,
allow_none
=
True
)
validate_floatlist
=
_listify_validator
(
validate_float
)
def
_validate_marker
(
s
):
try
:
return
validate_int
(
s
)
except
ValueError
as
e
:
try
:
return
validate_string
(
s
)
except
ValueError
as
e
:
raise
ValueError
(
'Supported markers are [string, int]'
)
from
e
_validate_markerlist
=
_listify_validator
(
_validate_marker
,
doc
=
'return a list of markers'
)
def
_validate_pathlike
(
s
):
if
isinstance
(
s
, (
str
,
os
.
PathLike
)):
# Store value as str because savefig.directory needs to distinguish
# between "" (cwd) and "." (cwd, but gets updated by user selections).
return
os
.
fsdecode
(
s
)
else
:
return
validate_string
(
s
)
def
validate_fonttype
(
s
):
"""
Confirm that this is a Postscript or PDF font type that we know how to
convert to.
"""
fonttypes
=
{
'type3'
:
3
,
'truetype'
:
42
}
try
:
fonttype
=
validate_int
(
s
)
except
ValueError
:
try
:
return
fonttypes
[
s
.
lower
()]
except
KeyError
as
e
:
raise
ValueError
(
'Supported Postscript/PDF font types are %s'
%
list
(
fonttypes
))
from
e
else
:
if
fonttype
not
in
fonttypes
.
values
():
raise
ValueError
(
'Supported Postscript/PDF font types are %s'
%
list
(
fonttypes
.
values
()))
return
fonttype
_auto_backend_sentinel
=
object
()
def
validate_backend
(
s
):
if
s
is
_auto_backend_sentinel
or
backend_registry
.
is_valid_backend
(
s
):
return
s
else
:
msg
=
(
f"'
{
s
}
' is not a valid value for backend; supported values are "
f"
{
backend_registry
.
list_all
()
}
"
)
raise
ValueError
(
msg
)
def
_validate_toolbar
(
s
):
s
=
ValidateInStrings
(
'toolbar'
, [
'None'
,
'toolbar2'
,
'toolmanager'
],
ignorecase
=
True
)(
s
)
if
s
==
'toolmanager'
:
_api
.
warn_external
(
"Treat the new Tool classes introduced in v1.5 as experimental "
"for now; the API and rcParam may change in future versions."
)
return
s
def
validate_color_or_inherit
(
s
):
"""Return a valid color arg."""
if
cbook
.
_str_equal
(
s
,
'inherit'
):
return
s
return
validate_color
(
s
)
def
validate_color_or_auto
(
s
):
if
cbook
.
_str_equal
(
s
,
'auto'
):
return
s
return
validate_color
(
s
)
def
_validate_color_or_edge
(
s
):
if
cbook
.
_str_equal
(
s
,
'edge'
):
return
s
return
validate_color
(
s
)
def
validate_color_for_prop_cycle
(
s
):
# N-th color cycle syntax can't go into the color cycle.
if
isinstance
(
s
,
str
)
and
re
.
match
(
"^C[0-9]$"
,
s
):
raise
ValueError
(
f"Cannot put cycle reference (
{
s
!r
}
) in prop_cycler"
)
return
validate_color
(
s
)
def
_validate_color_or_linecolor
(
s
):
if
cbook
.
_str_equal
(
s
,
'linecolor'
):
return
s
elif
cbook
.
_str_equal
(
s
,
'mfc'
)
or
cbook
.
_str_equal
(
s
,
'markerfacecolor'
):
return
'markerfacecolor'
elif
cbook
.
_str_equal
(
s
,
'mec'
)
or
cbook
.
_str_equal
(
s
,
'markeredgecolor'
):
return
'markeredgecolor'
elif
s
is
None
:
return
None
elif
isinstance
(
s
,
str
)
and
len
(
s
)
==
6
or
len
(
s
)
==
8
:
stmp
=
'#'
+
s
if
is_color_like
(
stmp
):
return
stmp
if
s
.
lower
()
==
'none'
:
return
None
elif
is_color_like
(
s
):
return
s
raise
ValueError
(
f'
{
s
!r
}
does not look like a color arg'
)
def
validate_color
(
s
):
"""Return a valid color arg."""
if
isinstance
(
s
,
str
):
if
s
.
lower
()
==
'none'
:
return
'none'
if
len
(
s
)
==
6
or
len
(
s
)
==
8
:
stmp
=
'#'
+
s
if
is_color_like
(
stmp
):
return
stmp
if
is_color_like
(
s
):
return
s
# If it is still valid, it must be a tuple (as a string from matplotlibrc).
try
:
color
=
ast
.
literal_eval
(
s
)
except
(
SyntaxError
,
ValueError
):
pass
else
:
if
is_color_like
(
color
):
return
color
raise
ValueError
(
f'
{
s
!r
}
does not look like a color arg'
)
def
_validate_color_or_None
(
s
):
if
s
is
None
or
cbook
.
_str_equal
(
s
,
"None"
):
return
None
return
validate_color
(
s
)
validate_colorlist
=
_listify_validator
(
validate_color
,
allow_stringlist
=
True
,
doc
=
'return a list of colorspecs'
)
def
_validate_cmap
(
s
):
_api
.
check_isinstance
((
str
,
Colormap
),
cmap
=
s
)
return
s
def
validate_aspect
(
s
):
if
s
in
(
'auto'
,
'equal'
):
return
s
try
:
return
float
(
s
)
except
ValueError
as
e
:
raise
ValueError
(
'not a valid aspect specification'
)
from
e
def
validate_fontsize_None
(
s
):
if
s
is
None
or
s
==
'None'
:
return
None
else
:
return
validate_fontsize
(
s
)
def
validate_fontsize
(
s
):
fontsizes
=
[
'xx-small'
,
'x-small'
,
'small'
,
'medium'
,
'large'
,
'x-large'
,
'xx-large'
,
'smaller'
,
'larger'
]
if
isinstance
(
s
,
str
):
s
=
s
.
lower
()
if
s
in
fontsizes
:
return
s
try
:
return
float
(
s
)
except
ValueError
as
e
:
raise
ValueError
(
"%s is not a valid font size. Valid font sizes "
"are %s."
%
(
s
,
", "
.
join
(
fontsizes
)))
from
e
validate_fontsizelist
=
_listify_validator
(
validate_fontsize
)
def
validate_fontweight
(
s
):
weights
=
[
'ultralight'
,
'light'
,
'normal'
,
'regular'
,
'book'
,
'medium'
,
'roman'
,
'semibold'
,
'demibold'
,
'demi'
,
'bold'
,
'heavy'
,
'extra bold'
,
'black'
]
# Note: Historically, weights have been case-sensitive in Matplotlib
if
s
in
weights
:
return
s
try
:
return
int
(
s
)
except
(
ValueError
,
TypeError
)
as
e
:
raise
ValueError
(
f'
{
s
}
is not a valid font weight.'
)
from
e
def
validate_fontstretch
(
s
):
stretchvalues
=
[
'ultra-condensed'
,
'extra-condensed'
,
'condensed'
,
'semi-condensed'
,
'normal'
,
'semi-expanded'
,
'expanded'
,
'extra-expanded'
,
'ultra-expanded'
]
# Note: Historically, stretchvalues have been case-sensitive in Matplotlib
if
s
in
stretchvalues
:
return
s
try
:
return
int
(
s
)
except
(
ValueError
,
TypeError
)
as
e
:
raise
ValueError
(
f'
{
s
}
is not a valid font stretch.'
)
from
e
def
validate_font_properties
(
s
):
parse_fontconfig_pattern
(
s
)
return
s
def
_validate_mathtext_fallback
(
s
):
_fallback_fonts
=
[
'cm'
,
'stix'
,
'stixsans'
]
if
isinstance
(
s
,
str
):
s
=
s
.
lower
()
if
s
is
None
or
s
==
'none'
:
return
None
elif
s
.
lower
()
in
_fallback_fonts
:
return
s
else
:
raise
ValueError
(
f"
{
s
}
is not a valid fallback font name. Valid fallback font "
f"names are
{
','
.
join
(
_fallback_fonts
)
}
. Passing 'None' will turn "
"fallback off."
)
def
validate_whiskers
(
s
):
try
:
return
_listify_validator
(
validate_float
,
n
=
2
)(
s
)
except
(
TypeError
,
ValueError
):
try
:
return
float
(
s
)
except
ValueError
as
e
:
raise
ValueError
(
"Not a valid whisker value [float, "
"(float, float)]"
)
from
e
def
validate_ps_distiller
(
s
):
if
isinstance
(
s
,
str
):
s
=
s
.
lower
()
if
s
in
(
'none'
,
None
,
'false'
,
False
):
return
None
else
:
return
ValidateInStrings
(
'ps.usedistiller'
, [
'ghostscript'
,
'xpdf'
])(
s
)
# A validator dedicated to the named line styles, based on the items in
# ls_mapper, and a list of possible strings read from Line2D.set_linestyle
_validate_named_linestyle
=
ValidateInStrings
(
'linestyle'
,
[
*
ls_mapper
.
keys
(),
*
ls_mapper
.
values
(),
'None'
,
'none'
,
' '
,
''
],
ignorecase
=
True
)
def
_validate_linestyle
(
ls
):
"""
A validator for all possible line styles, the named ones *and*
the on-off ink sequences.
"""
if
isinstance
(
ls
,
str
):
try
:
# Look first for a valid named line style, like '--' or 'solid'.
return
_validate_named_linestyle
(
ls
)
except
ValueError
:
pass
try
:
ls
=
ast
.
literal_eval
(
ls
)
# Parsing matplotlibrc.
except
(
SyntaxError
,
ValueError
):
pass
# Will error with the ValueError at the end.
def
_is_iterable_not_string_like
(
x
):
# Explicitly exclude bytes/bytearrays so that they are not
# nonsensically interpreted as sequences of numbers (codepoints).
return
np
.
iterable
(
x
)
and
not
isinstance
(
x
, (
str
,
bytes
,
bytearray
))
if
_is_iterable_not_string_like
(
ls
):
if
len
(
ls
)
==
2
and
_is_iterable_not_string_like
(
ls
[
1
]):
# (offset, (on, off, on, off, ...))
offset
,
onoff
=
ls
else
:
# For backcompat: (on, off, on, off, ...); the offset is implicit.
offset
=
0
onoff
=
ls
if
(
isinstance
(
offset
,
Real
)
and
len
(
onoff
)
%
2
==
0
and
all
(
isinstance
(
elem
,
Real
)
for
elem
in
onoff
)):
return
(
offset
,
onoff
)
raise
ValueError
(
f"linestyle
{
ls
!r
}
is not a valid on-off ink sequence."
)
def
_validate_linestyle_or_None
(
s
):
if
s
is
None
or
cbook
.
_str_equal
(
s
,
"None"
):
return
None
return
_validate_linestyle
(
s
)
validate_fillstyle
=
ValidateInStrings
(
'markers.fillstyle'
, [
'full'
,
'left'
,
'right'
,
'bottom'
,
'top'
,
'none'
])
validate_fillstylelist
=
_listify_validator
(
validate_fillstyle
)
def
validate_markevery
(
s
):
"""
Validate the markevery property of a Line2D object.
Parameters
----------
s : None, int, (int, int), slice, float, (float, float), or list[int]
Returns
-------
None, int, (int, int), slice, float, (float, float), or list[int]
"""
# Validate s against type slice float int and None
if
isinstance
(
s
, (
slice
,
float
,
int
,
type
(
None
))):
return
s
# Validate s against type tuple
if
isinstance
(
s
,
tuple
):
if
(
len
(
s
)
==
2
and
(
all
(
isinstance
(
e
,
int
)
for
e
in
s
)
or
all
(
isinstance
(
e
,
float
)
for
e
in
s
))):
return
s
else
:
raise
TypeError
(
"'markevery' tuple must be pair of ints or of floats"
)
# Validate s against type list
if
isinstance
(
s
,
list
):
if
all
(
isinstance
(
e
,
int
)
for
e
in
s
):
return
s
else
:
raise
TypeError
(
"'markevery' list must have all elements of type int"
)
raise
TypeError
(
"'markevery' is of an invalid type"
)
validate_markeverylist
=
_listify_validator
(
validate_markevery
)
def
validate_bbox
(
s
):
if
isinstance
(
s
,
str
):
s
=
s
.
lower
()
if
s
==
'tight'
:
return
s
if
s
==
'standard'
:
return
None
raise
ValueError
(
"bbox should be 'tight' or 'standard'"
)
elif
s
is
not
None
:
# Backwards compatibility. None is equivalent to 'standard'.
raise
ValueError
(
"bbox should be 'tight' or 'standard'"
)
return
s
def
validate_sketch
(
s
):
if
isinstance
(
s
,
str
):
s
=
s
.
lower
().
strip
()
if
s
.
startswith
(
"("
)
and
s
.
endswith
(
")"
):
s
=
s
[
1
:
-
1
]
if
s
==
'none'
or
s
is
None
:
return
None
try
:
return
tuple
(
_listify_validator
(
validate_float
,
n
=
3
)(
s
))
except
ValueError
as
exc
:
raise
ValueError
(
"Expected a (scale, length, randomness) tuple"
)
from
exc
def
_validate_greaterthan_minushalf
(
s
):
s
=
validate_float
(
s
)
if
s
>
-
0.5
:
return
s
else
:
raise
RuntimeError
(
f'Value must be >-0.5; got
{
s
}
'
)
def
_validate_greaterequal0_lessequal1
(
s
):
s
=
validate_float
(
s
)
if
0
<=
s
<=
1
:
return
s
else
:
raise
RuntimeError
(
f'Value must be >=0 and <=1; got
{
s
}
'
)
def
_validate_int_greaterequal0
(
s
):
s
=
validate_int
(
s
)
if
s
>=
0
:
return
s
else
:
raise
RuntimeError
(
f'Value must be >=0; got
{
s
}
'
)
def
validate_hatch
(
s
):
r"""
Validate a hatch pattern.
A hatch pattern string can have any sequence of the following
characters: ``\ / | - + * . x o O``.
"""
if
not
isinstance
(
s
,
str
):
raise
ValueError
(
"Hatch pattern must be a string"
)
_api
.
check_isinstance
(
str
,
hatch_pattern
=
s
)
unknown
=
set
(
s
)
-
{
'
\\
'
,
'/'
,
'|'
,
'-'
,
'+'
,
'*'
,
'.'
,
'x'
,
'o'
,
'O'
}
if
unknown
:
raise
ValueError
(
"Unknown hatch symbol(s): %s"
%
list
(
unknown
))
return
s
validate_hatchlist
=
_listify_validator
(
validate_hatch
)
validate_dashlist
=
_listify_validator
(
validate_floatlist
)
def
_validate_minor_tick_ndivs
(
n
):
"""
Validate ndiv parameter related to the minor ticks.
It controls the number of minor ticks to be placed between
two major ticks.
"""
if
cbook
.
_str_lower_equal
(
n
,
'auto'
):
return
n
try
:
n
=
_validate_int_greaterequal0
(
n
)
return
n
except
(
RuntimeError
,
ValueError
):
pass
raise
ValueError
(
"'tick.minor.ndivs' must be 'auto' or non-negative int"
)
_prop_validators
=
{
'color'
:
_listify_validator
(
validate_color_for_prop_cycle
,
allow_stringlist
=
True
),
'linewidth'
:
validate_floatlist
,
'linestyle'
:
_listify_validator
(
_validate_linestyle
),
'facecolor'
:
validate_colorlist
,
'edgecolor'
:
validate_colorlist
,
'joinstyle'
:
_listify_validator
(
JoinStyle
),
'capstyle'
:
_listify_validator
(
CapStyle
),
'fillstyle'
:
validate_fillstylelist
,
'markerfacecolor'
:
validate_colorlist
,
'markersize'
:
validate_floatlist
,
'markeredgewidth'
:
validate_floatlist
,
'markeredgecolor'
:
validate_colorlist
,
'markevery'
:
validate_markeverylist
,
'alpha'
:
validate_floatlist
,
'marker'
:
_validate_markerlist
,
'hatch'
:
validate_hatchlist
,
'dashes'
:
validate_dashlist
,
}
_prop_aliases
=
{
'c'
:
'color'
,
'lw'
:
'linewidth'
,
'ls'
:
'linestyle'
,
'fc'
:
'facecolor'
,
'ec'
:
'edgecolor'
,
'mfc'
:
'markerfacecolor'
,
'mec'
:
'markeredgecolor'
,
'mew'
:
'markeredgewidth'
,
'ms'
:
'markersize'
,
}
def
cycler
(
*
args
,
**
kwargs
):
"""
Create a `~cycler.Cycler` object much like :func:`cycler.cycler`,
but includes input validation.
Call signatures::
cycler(cycler)
cycler(label=values, label2=values2, ...)
cycler(label, values)
Form 1 copies a given `~cycler.Cycler` object.
Form 2 creates a `~cycler.Cycler` which cycles over one or more
properties simultaneously. If multiple properties are given, their
value lists must have the same length.
Form 3 creates a `~cycler.Cycler` for a single property. This form
exists for compatibility with the original cycler. Its use is
discouraged in favor of the kwarg form, i.e. ``cycler(label=values)``.
Parameters
----------
cycler : Cycler
Copy constructor for Cycler.
label : str
The property key. Must be a valid `.Artist` property.
For example, 'color' or 'linestyle'. Aliases are allowed,
such as 'c' for 'color' and 'lw' for 'linewidth'.
values : iterable
Finite-length iterable of the property values. These values
are validated and will raise a ValueError if invalid.
Returns
-------
Cycler
A new :class:`~cycler.Cycler` for the given properties.
Examples
--------
Creating a cycler for a single property:
>>> c = cycler(color=['red', 'green', 'blue'])
Creating a cycler for simultaneously cycling over multiple properties
(e.g. red circle, green plus, blue cross):
>>> c = cycler(color=['red', 'green', 'blue'],
... marker=['o', '+', 'x'])
"""
if
args
and
kwargs
:
raise
TypeError
(
"cycler() can only accept positional OR keyword "
"arguments -- not both."
)
elif
not
args
and
not
kwargs
:
raise
TypeError
(
"cycler() must have positional OR keyword arguments"
)
if
len
(
args
)
==
1
:
if
not
isinstance
(
args
[
0
],
Cycler
):
raise
TypeError
(
"If only one positional argument given, it must "
"be a Cycler instance."
)
return
validate_cycler
(
args
[
0
])
elif
len
(
args
)
==
2
:
pairs
=
[(
args
[
0
],
args
[
1
])]
elif
len
(
args
)
>
2
:
raise
_api
.
nargs_error
(
'cycler'
,
'0-2'
,
len
(
args
))
else
:
pairs
=
kwargs
.
items
()
validated
=
[]
for
prop
,
vals
in
pairs
:
norm_prop
=
_prop_aliases
.
get
(
prop
,
prop
)
validator
=
_prop_validators
.
get
(
norm_prop
,
None
)
if
validator
is
None
:
raise
TypeError
(
"Unknown artist property: %s"
%
prop
)
vals
=
validator
(
vals
)
# We will normalize the property names as well to reduce
# the amount of alias handling code elsewhere.
validated
.
append
((
norm_prop
,
vals
))
return
reduce
(
operator
.
add
, (
ccycler
(
k
,
v
)
for
k
,
v
in
validated
))
def
_parse_cycler_string
(
s
):
"""
Parse a string representation of a cycler into a Cycler object safely,
without using eval().
Accepts expressions like::
cycler('color', ['r', 'g', 'b'])
cycler('color', 'rgb') + cycler('linewidth', [1, 2, 3])
cycler(c='rgb', lw=[1, 2, 3])
cycler('c', 'rgb') * cycler('linestyle', ['-', '--'])
"""
try
:
tree
=
ast
.
parse
(
s
,
mode
=
'eval'
)
except
SyntaxError
as
e
:
raise
ValueError
(
f"Could not parse
{
s
!r
}
:
{
e
}
"
)
from
e
return
_eval_cycler_expr
(
tree
.
body
)
def
_eval_cycler_expr
(
node
):
"""Recursively evaluate an AST node to build a Cycler object."""
if
isinstance
(
node
,
ast
.
BinOp
):
left
=
_eval_cycler_expr
(
node
.
left
)
right
=
_eval_cycler_expr
(
node
.
right
)
if
isinstance
(
node
.
op
,
ast
.
Add
):
return
left
+
right
if
isinstance
(
node
.
op
,
ast
.
Mult
):
return
left
*
right
raise
ValueError
(
f"Unsupported operator:
{
type
(
node
.
op
).
__name__
}
"
)
if
isinstance
(
node
,
ast
.
Call
):
if
not
(
isinstance
(
node
.
func
,
ast
.
Name
)
and
node
.
func
.
id
in
(
'cycler'
,
'concat'
)):
raise
ValueError
(
"only the 'cycler()' and 'concat()' functions are allowed"
)
func
=
cycler
if
node
.
func
.
id
==
'cycler'
else
cconcat
args
=
[
_eval_cycler_expr
(
a
)
for
a
in
node
.
args
]
kwargs
=
{
kw
.
arg
:
_eval_cycler_expr
(
kw
.
value
)
for
kw
in
node
.
keywords
}
return
func
(
*
args
,
**
kwargs
)
if
isinstance
(
node
,
ast
.
Subscript
):
sl
=
node
.
slice
if
not
isinstance
(
sl
,
ast
.
Slice
):
raise
ValueError
(
"only slicing is supported, not indexing"
)
s
=
slice
(
ast
.
literal_eval
(
sl
.
lower
)
if
sl
.
lower
else
None
,
ast
.
literal_eval
(
sl
.
upper
)
if
sl
.
upper
else
None
,
ast
.
literal_eval
(
sl
.
step
)
if
sl
.
step
else
None
,
)
value
=
_eval_cycler_expr
(
node
.
value
)
return
value
[
s
]
# Allow literal values (int, strings, lists, tuples) as arguments
# to cycler() and concat().
try
:
return
ast
.
literal_eval
(
node
)
except
(
ValueError
,
TypeError
):
raise
ValueError
(
f"Unsupported expression in cycler string:
{
ast
.
dump
(
node
)
}
"
)
# A validator dedicated to the named legend loc
_validate_named_legend_loc
=
ValidateInStrings
(
'legend.loc'
,
[
"best"
,
"upper right"
,
"upper left"
,
"lower left"
,
"lower right"
,
"right"
,
"center left"
,
"center right"
,
"lower center"
,
"upper center"
,
"center"
],
ignorecase
=
True
)
def
_validate_legend_loc
(
loc
):
"""
Confirm that loc is a type which rc.Params["legend.loc"] supports.
.. versionadded:: 3.8
Parameters
----------
loc : str | int | (float, float) | str((float, float))
The location of the legend.
Returns
-------
loc : str | int | (float, float) or raise ValueError exception
The location of the legend.
"""
if
isinstance
(
loc
,
str
):
try
:
return
_validate_named_legend_loc
(
loc
)
except
ValueError
:
pass
try
:
loc
=
ast
.
literal_eval
(
loc
)
except
(
SyntaxError
,
ValueError
):
pass
if
isinstance
(
loc
,
int
):
if
0
<=
loc
<=
10
:
return
loc
if
isinstance
(
loc
,
tuple
):
if
len
(
loc
)
==
2
and
all
(
isinstance
(
e
,
Real
)
for
e
in
loc
):
return
loc
raise
ValueError
(
f"
{
loc
}
is not a valid legend location."
)
def
validate_cycler
(
s
):
"""Return a Cycler object from a string repr or the object itself."""
if
isinstance
(
s
,
str
):
try
:
s
=
_parse_cycler_string
(
s
)
except
Exception
as
e
:
raise
ValueError
(
f"
{
s
!r
}
is not a valid cycler construction:
{
e
}
"
)
from
e
if
isinstance
(
s
,
Cycler
):
cycler_inst
=
s
else
:
raise
ValueError
(
f"Object is not a string or Cycler instance:
{
s
!r
}
"
)
unknowns
=
cycler_inst
.
keys
-
(
set
(
_prop_validators
)
|
set
(
_prop_aliases
))
if
unknowns
:
raise
ValueError
(
"Unknown artist properties: %s"
%
unknowns
)
# Not a full validation, but it'll at least normalize property names
# A fuller validation would require v0.10 of cycler.
checker
=
set
()
for
prop
in
cycler_inst
.
keys
:
norm_prop
=
_prop_aliases
.
get
(
prop
,
prop
)
if
norm_prop
!=
prop
and
norm_prop
in
cycler_inst
.
keys
:
raise
ValueError
(
f"Cannot specify both
{
norm_prop
!r
}
and alias "
f"
{
prop
!r
}
in the same prop_cycle"
)
if
norm_prop
in
checker
:
raise
ValueError
(
f"Another property was already aliased to "
f"
{
norm_prop
!r
}
. Collision normalizing
{
prop
!r
}
."
)
checker
.
update
([
norm_prop
])
# This is just an extra-careful check, just in case there is some
# edge-case I haven't thought of.
assert
len
(
checker
)
==
len
(
cycler_inst
.
keys
)
# Now, it should be safe to mutate this cycler
for
prop
in
cycler_inst
.
keys
:
norm_prop
=
_prop_aliases
.
get
(
prop
,
prop
)
cycler_inst
.
change_key
(
prop
,
norm_prop
)
for
key
,
vals
in
cycler_inst
.
by_key
().
items
():
_prop_validators
[
key
](
vals
)
return
cycler_inst
def
validate_hist_bins
(
s
):
valid_strs
=
[
"auto"
,
"sturges"
,
"fd"
,
"doane"
,
"scott"
,
"rice"
,
"sqrt"
]
if
isinstance
(
s
,
str
)
and
s
in
valid_strs
:
return
s
try
:
return
int
(
s
)
except
(
TypeError
,
ValueError
):
pass
try
:
return
validate_floatlist
(
s
)
except
ValueError
:
pass
raise
ValueError
(
f"'hist.bins' must be one of
{
valid_strs
}
, an int or"
" a sequence of floats"
)
class
_ignorecase
(
list
):
"""A marker class indicating that a list-of-str is case-insensitive."""
def
_convert_validator_spec
(
key
,
conv
):
if
isinstance
(
conv
,
list
):
ignorecase
=
isinstance
(
conv
,
_ignorecase
)
return
ValidateInStrings
(
key
,
conv
,
ignorecase
=
ignorecase
)
else
:
return
conv
# Mapping of rcParams to validators.
# Converters given as lists or _ignorecase are converted to ValidateInStrings
# immediately below.
# The rcParams defaults are defined in lib/matplotlib/mpl-data/matplotlibrc, which
# gets copied to matplotlib/mpl-data/matplotlibrc by the setup script.
_validators
=
{
"backend"
:
validate_backend
,
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL