/
__init__.py
1516 lines (1249 loc) · 52.4 KB
/
__init__.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
"""
An object-oriented plotting library.
A procedural interface is provided by the companion pyplot module,
which may be imported directly, e.g.::
import matplotlib.pyplot as plt
or using ipython::
ipython
at your terminal, followed by::
In [1]: %matplotlib
In [2]: import matplotlib.pyplot as plt
at the ipython shell prompt.
For the most part, direct use of the explicit object-oriented library is
encouraged when programming; the implicit pyplot interface is primarily for
working interactively. The exceptions to this suggestion are the pyplot
functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and
`.pyplot.savefig`, which can greatly simplify scripting. See
:ref:`api_interfaces` for an explanation of the tradeoffs between the implicit
and explicit interfaces.
Modules include:
:mod:`matplotlib.axes`
The `~.axes.Axes` class. Most pyplot functions are wrappers for
`~.axes.Axes` methods. The axes module is the highest level of OO
access to the library.
:mod:`matplotlib.figure`
The `.Figure` class.
:mod:`matplotlib.artist`
The `.Artist` base class for all classes that draw things.
:mod:`matplotlib.lines`
The `.Line2D` class for drawing lines and markers.
:mod:`matplotlib.patches`
Classes for drawing polygons.
:mod:`matplotlib.text`
The `.Text` and `.Annotation` classes.
:mod:`matplotlib.image`
The `.AxesImage` and `.FigureImage` classes.
:mod:`matplotlib.collections`
Classes for efficient drawing of groups of lines or polygons.
:mod:`matplotlib.colors`
Color specifications and making colormaps.
:mod:`matplotlib.cm`
Colormaps, and the `.ScalarMappable` mixin class for providing color
mapping functionality to other classes.
:mod:`matplotlib.ticker`
Calculation of tick mark locations and formatting of tick labels.
:mod:`matplotlib.backends`
A subpackage with modules for various GUI libraries and output formats.
The base matplotlib namespace includes:
`~matplotlib.rcParams`
Default configuration settings; their defaults may be overridden using
a :file:`matplotlibrc` file.
`~matplotlib.use`
Setting the Matplotlib backend. This should be called before any
figure is created, because it is not possible to switch between
different GUI backends after that.
The following environment variables can be used to customize the behavior:
:envvar:`MPLBACKEND`
This optional variable can be set to choose the Matplotlib backend. See
:ref:`what-is-a-backend`.
:envvar:`MPLCONFIGDIR`
This is the directory used to store user customizations to
Matplotlib, as well as some caches to improve performance. If
:envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib`
and :file:`{HOME}/.cache/matplotlib` are used on Linux, and
:file:`{HOME}/.matplotlib` on other platforms, if they are
writable. Otherwise, the Python standard library's `tempfile.gettempdir`
is used to find a base directory in which the :file:`matplotlib`
subdirectory is created.
Matplotlib was initially written by John D. Hunter (1968-2012) and is now
developed and maintained by a host of others.
Occasionally the internal documentation (python docstrings) will refer
to MATLAB®, a registered trademark of The MathWorks, Inc.
"""
__all__ = [
"__bibtex__",
"__version__",
"__version_info__",
"set_loglevel",
"ExecutableNotFoundError",
"get_configdir",
"get_cachedir",
"get_data_path",
"matplotlib_fname",
"MatplotlibDeprecationWarning",
"RcParams",
"rc_params",
"rc_params_from_file",
"rcParamsDefault",
"rcParams",
"rcParamsOrig",
"defaultParams",
"rc",
"rcdefaults",
"rc_file_defaults",
"rc_file",
"rc_context",
"use",
"get_backend",
"interactive",
"is_interactive",
"colormaps",
"color_sequences",
]
import atexit
from collections import namedtuple
from collections.abc import MutableMapping
import contextlib
import functools
import importlib
import inspect
from inspect import Parameter
import locale
import logging
import os
from pathlib import Path
import pprint
import re
import shutil
import subprocess
import sys
import tempfile
from packaging.version import parse as parse_version
# cbook must import matplotlib only within function
# definitions, so it is safe to import from it here.
from . import _api, _version, cbook, _docstring, rcsetup
from matplotlib.cbook import sanitize_sequence
from matplotlib._api import MatplotlibDeprecationWarning
from matplotlib.rcsetup import cycler # noqa: F401
from matplotlib.rcsetup import validate_backend
_log = logging.getLogger(__name__)
__bibtex__ = r"""@Article{Hunter:2007,
Author = {Hunter, J. D.},
Title = {Matplotlib: A 2D graphics environment},
Journal = {Computing in Science \& Engineering},
Volume = {9},
Number = {3},
Pages = {90--95},
abstract = {Matplotlib is a 2D graphics package used for Python
for application development, interactive scripting, and
publication-quality image generation across user
interfaces and operating systems.},
publisher = {IEEE COMPUTER SOC},
year = 2007
}"""
# modelled after sys.version_info
_VersionInfo = namedtuple('_VersionInfo',
'major, minor, micro, releaselevel, serial')
def _parse_to_version_info(version_str):
"""
Parse a version string to a namedtuple analogous to sys.version_info.
See:
https://packaging.pypa.io/en/latest/version.html#packaging.version.parse
https://docs.python.org/3/library/sys.html#sys.version_info
"""
v = parse_version(version_str)
if v.pre is None and v.post is None and v.dev is None:
return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)
elif v.dev is not None:
return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)
elif v.pre is not None:
releaselevel = {
'a': 'alpha',
'b': 'beta',
'rc': 'candidate'}.get(v.pre[0], 'alpha')
return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])
else:
# fallback for v.post: guess-next-dev scheme from setuptools_scm
return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)
def _get_version():
"""Return the version string used for __version__."""
# Only shell out to a git subprocess if really needed, i.e. when we are in
# a matplotlib git repo but not in a shallow clone, such as those used by
# CI, as the latter would trigger a warning from setuptools_scm.
root = Path(__file__).resolve().parents[2]
if ((root / ".matplotlib-repo").exists()
and (root / ".git").exists()
and not (root / ".git/shallow").exists()):
try:
import setuptools_scm
except ImportError:
pass
else:
return setuptools_scm.get_version(
root=root,
version_scheme="release-branch-semver",
local_scheme="node-and-date",
fallback_version=_version.version,
)
# Get the version from the _version.py file if not in repo or setuptools_scm is
# unavailable.
return _version.version
@_api.caching_module_getattr
class __getattr__:
__version__ = property(lambda self: _get_version())
__version_info__ = property(
lambda self: _parse_to_version_info(self.__version__))
def _check_versions():
# Quickfix to ensure Microsoft Visual C++ redistributable
# DLLs are loaded before importing kiwisolver
from . import ft2font # noqa: F401
for modname, minver in [
("cycler", "0.10"),
("dateutil", "2.7"),
("kiwisolver", "1.3.1"),
("numpy", "1.23"),
("pyparsing", "2.3.1"),
]:
module = importlib.import_module(modname)
if parse_version(module.__version__) < parse_version(minver):
raise ImportError(f"Matplotlib requires {modname}>={minver}; "
f"you have {module.__version__}")
_check_versions()
# The decorator ensures this always returns the same handler (and it is only
# attached once).
@functools.cache
def _ensure_handler():
"""
The first time this function is called, attach a `StreamHandler` using the
same format as `logging.basicConfig` to the Matplotlib root logger.
Return this handler every time this function is called.
"""
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
_log.addHandler(handler)
return handler
def set_loglevel(level):
"""
Configure Matplotlib's logging levels.
Matplotlib uses the standard library `logging` framework under the root
logger 'matplotlib'. This is a helper function to:
- set Matplotlib's root logger level
- set the root logger handler's level, creating the handler
if it does not exist yet
Typically, one should call ``set_loglevel("info")`` or
``set_loglevel("debug")`` to get additional debugging information.
Users or applications that are installing their own logging handlers
may want to directly manipulate ``logging.getLogger('matplotlib')`` rather
than use this function.
Parameters
----------
level : {"notset", "debug", "info", "warning", "error", "critical"}
The log level of the handler.
Notes
-----
The first time this function is called, an additional handler is attached
to Matplotlib's root handler; this handler is reused every time and this
function simply manipulates the logger and handler's level.
"""
_log.setLevel(level.upper())
_ensure_handler().setLevel(level.upper())
def _logged_cached(fmt, func=None):
"""
Decorator that logs a function's return value, and memoizes that value.
After ::
@_logged_cached(fmt)
def func(): ...
the first call to *func* will log its return value at the DEBUG level using
%-format string *fmt*, and memoize it; later calls to *func* will directly
return that value.
"""
if func is None: # Return the actual decorator.
return functools.partial(_logged_cached, fmt)
called = False
ret = None
@functools.wraps(func)
def wrapper(**kwargs):
nonlocal called, ret
if not called:
ret = func(**kwargs)
called = True
_log.debug(fmt, ret)
return ret
return wrapper
_ExecInfo = namedtuple("_ExecInfo", "executable raw_version version")
class ExecutableNotFoundError(FileNotFoundError):
"""
Error raised when an executable that Matplotlib optionally
depends on can't be found.
"""
pass
@functools.cache
def _get_executable_info(name):
"""
Get the version of some executable that Matplotlib optionally depends on.
.. warning::
The list of executables that this function supports is set according to
Matplotlib's internal needs, and may change without notice.
Parameters
----------
name : str
The executable to query. The following values are currently supported:
"dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This
list is subject to change without notice.
Returns
-------
tuple
A namedtuple with fields ``executable`` (`str`) and ``version``
(`packaging.Version`, or ``None`` if the version cannot be determined).
Raises
------
ExecutableNotFoundError
If the executable is not found or older than the oldest version
supported by Matplotlib. For debugging purposes, it is also
possible to "hide" an executable from Matplotlib by adding it to the
:envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated
list), which must be set prior to any calls to this function.
ValueError
If the executable is not one that we know how to query.
"""
def impl(args, regex, min_ver=None, ignore_exit_code=False):
# Execute the subprocess specified by args; capture stdout and stderr.
# Search for a regex match in the output; if the match succeeds, the
# first group of the match is the version.
# Return an _ExecInfo if the executable exists, and has a version of
# at least min_ver (if set); else, raise ExecutableNotFoundError.
try:
output = subprocess.check_output(
args, stderr=subprocess.STDOUT,
text=True, errors="replace")
except subprocess.CalledProcessError as _cpe:
if ignore_exit_code:
output = _cpe.output
else:
raise ExecutableNotFoundError(str(_cpe)) from _cpe
except OSError as _ose:
raise ExecutableNotFoundError(str(_ose)) from _ose
match = re.search(regex, output)
if match:
raw_version = match.group(1)
version = parse_version(raw_version)
if min_ver is not None and version < parse_version(min_ver):
raise ExecutableNotFoundError(
f"You have {args[0]} version {version} but the minimum "
f"version supported by Matplotlib is {min_ver}")
return _ExecInfo(args[0], raw_version, version)
else:
raise ExecutableNotFoundError(
f"Failed to determine the version of {args[0]} from "
f"{' '.join(args)}, which output {output}")
if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","):
raise ExecutableNotFoundError(f"{name} was hidden")
if name == "dvipng":
return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
elif name == "gs":
execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
if sys.platform == "win32" else
["gs"])
for e in execs:
try:
return impl([e, "--version"], "(.*)", "9")
except ExecutableNotFoundError:
pass
message = "Failed to find a Ghostscript installation"
raise ExecutableNotFoundError(message)
elif name == "inkscape":
try:
# Try headless option first (needed for Inkscape version < 1.0):
return impl(["inkscape", "--without-gui", "-V"],
"Inkscape ([^ ]*)")
except ExecutableNotFoundError:
pass # Suppress exception chaining.
# If --without-gui is not accepted, we may be using Inkscape >= 1.0 so
# try without it:
return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")
elif name == "magick":
if sys.platform == "win32":
# Check the registry to avoid confusing ImageMagick's convert with
# Windows's builtin convert.exe.
import winreg
binpath = ""
for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
try:
with winreg.OpenKeyEx(
winreg.HKEY_LOCAL_MACHINE,
r"Software\Imagemagick\Current",
0, winreg.KEY_QUERY_VALUE | flag) as hkey:
binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
except OSError:
pass
path = None
if binpath:
for name in ["convert.exe", "magick.exe"]:
candidate = Path(binpath, name)
if candidate.exists():
path = str(candidate)
break
if path is None:
raise ExecutableNotFoundError(
"Failed to find an ImageMagick installation")
else:
path = "convert"
info = impl([path, "--version"], r"^Version: ImageMagick (\S*)")
if info.raw_version == "7.0.10-34":
# https://github.com/ImageMagick/ImageMagick/issues/2720
raise ExecutableNotFoundError(
f"You have ImageMagick {info.version}, which is unsupported")
return info
elif name == "pdftocairo":
return impl(["pdftocairo", "-v"], "pdftocairo version (.*)")
elif name == "pdftops":
info = impl(["pdftops", "-v"], "^pdftops version (.*)",
ignore_exit_code=True)
if info and not (
3 <= info.version.major or
# poppler version numbers.
parse_version("0.9") <= info.version < parse_version("1.0")):
raise ExecutableNotFoundError(
f"You have pdftops version {info.version} but the minimum "
f"version supported by Matplotlib is 3.0")
return info
else:
raise ValueError(f"Unknown executable: {name!r}")
def _get_xdg_config_dir():
"""
Return the XDG configuration directory, according to the XDG base
directory spec:
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
"""
return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")
def _get_xdg_cache_dir():
"""
Return the XDG cache directory, according to the XDG base directory spec:
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
"""
return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")
def _get_config_or_cache_dir(xdg_base_getter):
configdir = os.environ.get('MPLCONFIGDIR')
if configdir:
configdir = Path(configdir).resolve()
elif sys.platform.startswith(('linux', 'freebsd')):
# Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first,
# as _xdg_base_getter can throw.
configdir = Path(xdg_base_getter(), "matplotlib")
else:
configdir = Path.home() / ".matplotlib"
try:
configdir.mkdir(parents=True, exist_ok=True)
except OSError:
pass
else:
if os.access(str(configdir), os.W_OK) and configdir.is_dir():
return str(configdir)
# If the config or cache directory cannot be created or is not a writable
# directory, create a temporary one.
try:
tmpdir = tempfile.mkdtemp(prefix="matplotlib-")
except OSError as exc:
raise OSError(
f"Matplotlib requires access to a writable cache directory, but the "
f"default path ({configdir}) is not a writable directory, and a temporary "
f"directory could not be created; set the MPLCONFIGDIR environment "
f"variable to a writable directory") from exc
os.environ["MPLCONFIGDIR"] = tmpdir
atexit.register(shutil.rmtree, tmpdir)
_log.warning(
"Matplotlib created a temporary cache directory at %s because the default path "
"(%s) is not a writable directory; it is highly recommended to set the "
"MPLCONFIGDIR environment variable to a writable directory, in particular to "
"speed up the import of Matplotlib and to better support multiprocessing.",
tmpdir, configdir)
return tmpdir
@_logged_cached('CONFIGDIR=%s')
def get_configdir():
"""
Return the string path of the configuration directory.
The directory is chosen as follows:
1. If the MPLCONFIGDIR environment variable is supplied, choose that.
2. On Linux, follow the XDG specification and look first in
``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other
platforms, choose ``$HOME/.matplotlib``.
3. If the chosen directory exists and is writable, use that as the
configuration directory.
4. Else, create a temporary directory, and use it as the configuration
directory.
"""
return _get_config_or_cache_dir(_get_xdg_config_dir)
@_logged_cached('CACHEDIR=%s')
def get_cachedir():
"""
Return the string path of the cache directory.
The procedure used to find the directory is the same as for
`get_configdir`, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead.
"""
return _get_config_or_cache_dir(_get_xdg_cache_dir)
@_logged_cached('matplotlib data path: %s')
def get_data_path():
"""Return the path to Matplotlib data."""
return str(Path(__file__).with_name("mpl-data"))
def matplotlib_fname():
"""
Get the location of the config file.
The file location is determined in the following order
- ``$PWD/matplotlibrc``
- ``$MATPLOTLIBRC`` if it is not a directory
- ``$MATPLOTLIBRC/matplotlibrc``
- ``$MPLCONFIGDIR/matplotlibrc``
- On Linux,
- ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
is defined)
- or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
is not defined)
- On other platforms,
- ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
- Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
exist.
"""
def gen_candidates():
# rely on down-stream code to make absolute. This protects us
# from having to directly get the current working directory
# which can fail if the user has ended up with a cwd that is
# non-existent.
yield 'matplotlibrc'
try:
matplotlibrc = os.environ['MATPLOTLIBRC']
except KeyError:
pass
else:
yield matplotlibrc
yield os.path.join(matplotlibrc, 'matplotlibrc')
yield os.path.join(get_configdir(), 'matplotlibrc')
yield os.path.join(get_data_path(), 'matplotlibrc')
for fname in gen_candidates():
if os.path.exists(fname) and not os.path.isdir(fname):
return fname
raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
"install is broken")
# rcParams deprecated and automatically mapped to another key.
# Values are tuples of (version, new_name, f_old2new, f_new2old).
_deprecated_map = {}
# rcParams deprecated; some can manually be mapped to another key.
# Values are tuples of (version, new_name_or_None).
_deprecated_ignore_map = {}
# rcParams deprecated; can use None to suppress warnings; remain actually
# listed in the rcParams.
# Values are tuples of (version,)
_deprecated_remain_as_none = {}
@_docstring.Substitution(
"\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower)))
)
class RcParams(MutableMapping, dict):
"""
A dict-like key-value store for config parameters, including validation.
Validating functions are defined and associated with rc parameters in
:mod:`matplotlib.rcsetup`.
The list of rcParams is:
%s
See Also
--------
:ref:`customizing-with-matplotlibrc-files`
"""
validate = rcsetup._validators
# validate values on the way in
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def _set(self, key, val):
"""
Directly write data bypassing deprecation and validation logic.
Notes
-----
As end user or downstream library you almost always should use
``rcParams[key] = val`` and not ``_set()``.
There are only very few special cases that need direct data access.
These cases previously used ``dict.__setitem__(rcParams, key, val)``,
which is now deprecated and replaced by ``rcParams._set(key, val)``.
Even though private, we guarantee API stability for ``rcParams._set``,
i.e. it is subject to Matplotlib's API and deprecation policy.
:meta public:
"""
dict.__setitem__(self, key, val)
def _get(self, key):
"""
Directly read data bypassing deprecation, backend and validation
logic.
Notes
-----
As end user or downstream library you almost always should use
``val = rcParams[key]`` and not ``_get()``.
There are only very few special cases that need direct data access.
These cases previously used ``dict.__getitem__(rcParams, key, val)``,
which is now deprecated and replaced by ``rcParams._get(key)``.
Even though private, we guarantee API stability for ``rcParams._get``,
i.e. it is subject to Matplotlib's API and deprecation policy.
:meta public:
"""
return dict.__getitem__(self, key)
def __setitem__(self, key, val):
try:
if key in _deprecated_map:
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
_api.warn_deprecated(
version, name=key, obj_type="rcparam", alternative=alt_key)
key = alt_key
val = alt_val(val)
elif key in _deprecated_remain_as_none and val is not None:
version, = _deprecated_remain_as_none[key]
_api.warn_deprecated(version, name=key, obj_type="rcparam")
elif key in _deprecated_ignore_map:
version, alt_key = _deprecated_ignore_map[key]
_api.warn_deprecated(
version, name=key, obj_type="rcparam", alternative=alt_key)
return
elif key == 'backend':
if val is rcsetup._auto_backend_sentinel:
if 'backend' in self:
return
try:
cval = self.validate[key](val)
except ValueError as ve:
raise ValueError(f"Key {key}: {ve}") from None
self._set(key, cval)
except KeyError as err:
raise KeyError(
f"{key} is not a valid rc parameter (see rcParams.keys() for "
f"a list of valid parameters)") from err
def __getitem__(self, key):
if key in _deprecated_map:
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
_api.warn_deprecated(
version, name=key, obj_type="rcparam", alternative=alt_key)
return inverse_alt(self._get(alt_key))
elif key in _deprecated_ignore_map:
version, alt_key = _deprecated_ignore_map[key]
_api.warn_deprecated(
version, name=key, obj_type="rcparam", alternative=alt_key)
return self._get(alt_key) if alt_key else None
# In theory, this should only ever be used after the global rcParams
# has been set up, but better be safe e.g. in presence of breakpoints.
elif key == "backend" and self is globals().get("rcParams"):
val = self._get(key)
if val is rcsetup._auto_backend_sentinel:
from matplotlib import pyplot as plt
plt.switch_backend(rcsetup._auto_backend_sentinel)
return self._get(key)
def _get_backend_or_none(self):
"""Get the requested backend, if any, without triggering resolution."""
backend = self._get("backend")
return None if backend is rcsetup._auto_backend_sentinel else backend
def __repr__(self):
class_name = self.__class__.__name__
indent = len(class_name) + 1
with _api.suppress_matplotlib_deprecation_warning():
repr_split = pprint.pformat(dict(self), indent=1,
width=80 - indent).split('\n')
repr_indented = ('\n' + ' ' * indent).join(repr_split)
return f'{class_name}({repr_indented})'
def __str__(self):
return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
def __iter__(self):
"""Yield sorted list of keys."""
with _api.suppress_matplotlib_deprecation_warning():
yield from sorted(dict.__iter__(self))
def __len__(self):
return dict.__len__(self)
def find_all(self, pattern):
"""
Return the subset of this RcParams dictionary whose keys match,
using :func:`re.search`, the given ``pattern``.
.. note::
Changes to the returned dictionary are *not* propagated to
the parent RcParams dictionary.
"""
pattern_re = re.compile(pattern)
return RcParams((key, value)
for key, value in self.items()
if pattern_re.search(key))
def copy(self):
"""Copy this RcParams instance."""
rccopy = RcParams()
for k in self: # Skip deprecations and revalidation.
rccopy._set(k, self._get(k))
return rccopy
def rc_params(fail_on_error=False):
"""Construct a `RcParams` instance from the default Matplotlib rc file."""
return rc_params_from_file(matplotlib_fname(), fail_on_error)
@functools.cache
def _get_ssl_context():
try:
import certifi
except ImportError:
_log.debug("Could not import certifi.")
return None
import ssl
return ssl.create_default_context(cafile=certifi.where())
@contextlib.contextmanager
def _open_file_or_url(fname):
if (isinstance(fname, str)
and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))):
import urllib.request
ssl_ctx = _get_ssl_context()
if ssl_ctx is None:
_log.debug(
"Could not get certifi ssl context, https may not work."
)
with urllib.request.urlopen(fname, context=ssl_ctx) as f:
yield (line.decode('utf-8') for line in f)
else:
fname = os.path.expanduser(fname)
with open(fname, encoding='utf-8') as f:
yield f
def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):
"""
Construct a `RcParams` instance from file *fname*.
Unlike `rc_params_from_file`, the configuration class only contains the
parameters specified in the file (i.e. default values are not filled in).
Parameters
----------
fname : path-like
The loaded file.
transform : callable, default: the identity function
A function called on each individual line of the file to transform it,
before further parsing.
fail_on_error : bool, default: False
Whether invalid entries should result in an exception or a warning.
"""
import matplotlib as mpl
rc_temp = {}
with _open_file_or_url(fname) as fd:
try:
for line_no, line in enumerate(fd, 1):
line = transform(line)
strippedline = cbook._strip_comment(line)
if not strippedline:
continue
tup = strippedline.split(':', 1)
if len(tup) != 2:
_log.warning('Missing colon in file %r, line %d (%r)',
fname, line_no, line.rstrip('\n'))
continue
key, val = tup
key = key.strip()
val = val.strip()
if val.startswith('"') and val.endswith('"'):
val = val[1:-1] # strip double quotes
if key in rc_temp:
_log.warning('Duplicate key in file %r, line %d (%r)',
fname, line_no, line.rstrip('\n'))
rc_temp[key] = (val, line, line_no)
except UnicodeDecodeError:
_log.warning('Cannot decode configuration file %r as utf-8.',
fname)
raise
config = RcParams()
for key, (val, line, line_no) in rc_temp.items():
if key in rcsetup._validators:
if fail_on_error:
config[key] = val # try to convert to proper type or raise
else:
try:
config[key] = val # try to convert to proper type or skip
except Exception as msg:
_log.warning('Bad value in file %r, line %d (%r): %s',
fname, line_no, line.rstrip('\n'), msg)
elif key in _deprecated_ignore_map:
version, alt_key = _deprecated_ignore_map[key]
_api.warn_deprecated(
version, name=key, alternative=alt_key, obj_type='rcparam',
addendum="Please update your matplotlibrc.")
else:
# __version__ must be looked up as an attribute to trigger the
# module-level __getattr__.
version = ('main' if '.post' in mpl.__version__
else f'v{mpl.__version__}')
_log.warning("""
Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)
You probably need to get an updated matplotlibrc file from
https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc
or from the matplotlib source distribution""",
dict(key=key, fname=fname, line_no=line_no,
line=line.rstrip('\n'), version=version))
return config
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
"""
Construct a `RcParams` from file *fname*.
Parameters
----------
fname : str or path-like
A file with Matplotlib rc settings.
fail_on_error : bool
If True, raise an error when the parser fails to convert a parameter.
use_default_template : bool
If True, initialize with default parameters before updating with those
in the given file. If False, the configuration class only contains the
parameters specified in the file. (Useful for updating dicts.)
"""
config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)
if not use_default_template:
return config_from_file
with _api.suppress_matplotlib_deprecation_warning():
config = RcParams({**rcParamsDefault, **config_from_file})
if "".join(config['text.latex.preamble']):
_log.info("""
*****************************************************************
You have the following UNSUPPORTED LaTeX preamble customizations:
%s
Please do not ask for support with these customizations active.
*****************************************************************
""", '\n'.join(config['text.latex.preamble']))
_log.debug('loaded rc file %s', fname)
return config
# When constructing the global instances, we need to perform certain updates
# by explicitly calling the superclass (dict.update, dict.items) to avoid
# triggering resolution of _auto_backend_sentinel.
rcParamsDefault = _rc_params_in_file(
cbook._get_data_path("matplotlibrc"),
# Strip leading comment.
transform=lambda line: line[1:] if line.startswith("#") else line,
fail_on_error=True)
dict.update(rcParamsDefault, rcsetup._hardcoded_defaults)
# Normally, the default matplotlibrc file contains *no* entry for backend (the
# corresponding line starts with ##, not #; we fill on _auto_backend_sentinel
# in that case. However, packagers can set a different default backend
# (resulting in a normal `#backend: foo` line) in which case we should *not*
# fill in _auto_backend_sentinel.
dict.setdefault(rcParamsDefault, "backend", rcsetup._auto_backend_sentinel)
rcParams = RcParams() # The global instance.
dict.update(rcParams, dict.items(rcParamsDefault))
dict.update(rcParams, _rc_params_in_file(matplotlib_fname()))
rcParamsOrig = rcParams.copy()
with _api.suppress_matplotlib_deprecation_warning():
# This also checks that all rcParams are indeed listed in the template.
# Assigning to rcsetup.defaultParams is left only for backcompat.
defaultParams = rcsetup.defaultParams = {
# We want to resolve deprecated rcParams, but not backend...
key: [(rcsetup._auto_backend_sentinel if key == "backend" else
rcParamsDefault[key]),
validator]
for key, validator in rcsetup._validators.items()}
if rcParams['axes.formatter.use_locale']:
locale.setlocale(locale.LC_ALL, '')
def rc(group, **kwargs):
"""
Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,
for ``lines.linewidth`` the group is ``lines``, for
``axes.facecolor``, the group is ``axes``, and so on. Group may