3
3
4
4
``use``
5
5
Select style sheet to override the current matplotlib settings.
6
+ ``context``
7
+ Context manager to use a style sheet temporarily.
6
8
``available``
7
9
List available style sheets.
8
10
``library``
9
11
A dictionary of style names and matplotlib settings.
10
12
"""
11
13
import os
12
14
import re
15
+ import contextlib
13
16
14
17
import numpy as np
15
18
import matplotlib as mpl
16
19
17
20
18
- __all__ = ['use' , 'available' , 'library' ]
21
+ __all__ = ['use' , 'context' , ' available' , 'library' , 'reload_library ' ]
19
22
20
23
21
24
_here = os .path .abspath (os .path .dirname (__file__ ))
22
25
BASE_LIBRARY_PATH = os .path .join (_here , 'stylelib' )
23
26
# Users may want multiple library paths, so store a list of paths.
24
27
USER_LIBRARY_PATHS = [os .path .join ('~' , '.matplotlib' , 'stylelib' )]
25
- STYLE_FILE_PATTERN = re .compile ('([\S]+).style$' )
28
+ STYLE_EXTENSION = 'style'
29
+ STYLE_FILE_PATTERN = re .compile ('([\S]+).%s$' % STYLE_EXTENSION )
26
30
27
31
28
32
def is_style_file (filename ):
@@ -31,7 +35,7 @@ def is_style_file(filename):
31
35
32
36
33
37
def use (name ):
34
- """Use matplotlib rc parameters from a pre-defined name or from a file.
38
+ """Use matplotlib style settings from a known style sheet or from a file.
35
39
36
40
Parameters
37
41
----------
@@ -55,6 +59,28 @@ def use(name):
55
59
mpl .rcParams .update (library [style ])
56
60
57
61
62
+ @contextlib .contextmanager
63
+ def context (name , after_reset = False ):
64
+ """Context manager for using style settings temporarily.
65
+
66
+ Parameters
67
+ ----------
68
+ name : str or list of str
69
+ Name of style or path/URL to a style file. For a list of available
70
+ style names, see `style.available`. If given a list, each style is
71
+ applied from first to last in the list.
72
+ after_reset : bool
73
+ If True, apply style after resetting settings to their defaults;
74
+ otherwise, apply style on top of the current settings.
75
+ """
76
+ initial_settings = mpl .rcParams .copy ()
77
+ if after_reset :
78
+ mpl .rcdefaults ()
79
+ use (name )
80
+ yield
81
+ mpl .rcParams .update (initial_settings )
82
+
83
+
58
84
def load_base_library ():
59
85
"""Load style library defined in this package."""
60
86
library = dict ()
@@ -114,5 +140,13 @@ def update_nested_dict(main_dict, new_dict):
114
140
# Load style library
115
141
# ==================
116
142
_base_library = load_base_library ()
117
- library = update_user_library (_base_library )
118
- available = library .keys ()
143
+
144
+ library = None
145
+ available = []
146
+
147
+ def reload_library ():
148
+ """Reload style library."""
149
+ global library , available
150
+ library = update_user_library (_base_library )
151
+ available [:] = library .keys ()
152
+ reload_library ()
0 commit comments