py_plt_styler 0.0.12__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.3
2
+ Name: py_plt_styler
3
+ Version: 0.0.12
4
+ Summary: A collection of stylesheets and default values for Python matplotlib figures.
5
+ Author: Bela Vogler
6
+ Author-email: Bela Vogler <bela.vogler@uni-jena.de>
7
+ Requires-Dist: matplotlib>=3.11.2
8
+ Requires-Dist: numpy>=2.5.5
9
+ Requires-Python: >=3.12
10
+ Description-Content-Type: text/markdown
11
+
12
+ # py_plt_styler
13
+ A simple package to provide a collection of stylesheets and default values for Python matplotlib figures. The goal is to make it easy to create visually appealing and consistent plots with minimal effort.
14
+
15
+ I will add more stylesheets and default values in the future! If you have any suggestions or want to contribute, feel free to open an issue or a pull request.
16
+
17
+ # Installation
18
+ You can install py_plt_styler using pip:
19
+ ```bash
20
+ pip install py_plt_styler
21
+ ```
22
+
23
+ # Usage
24
+ To use py_plt_styler, simply import the desired stylesheet and apply it to your matplotlib figures. For example:
25
+ ```python
26
+ import matplotlib.pyplot as plt
27
+ from py_plt_styler import py_plt_styler
28
+
29
+ # Apply the default stylesheet
30
+ py_plt_styler().apply()
31
+
32
+ # Apply a predefined stylesheet (e.g., "dark")
33
+ py_plt_styler().set_stylesheet("dark").apply()
34
+
35
+ # Apply a custom stylesheet - must be json (see below for an example)
36
+ py_plt_styler().set_stylesheet("path/to/stylesheet.json").apply()
37
+
38
+ # Change the font
39
+ py_plt_styler().set_font(family="Arial", weight="normal").apply()
40
+
41
+ # Because the py_plt_styler is a singleton and the methods return the instance itself, you can chain the methods together for conveniently readable code:
42
+ py_plt_styler().set_stylesheet("dark").set_font(family="Arial", weight="normal").apply()
43
+
44
+ # The py_plt_styler inclused default parameters for the following plot types:
45
+ # - Line plots
46
+ # - Scatter plots
47
+ # - Box plots
48
+ # - Histograms
49
+
50
+ lineplot_defaults = py_plt_styler().get_default_parameters("lineplot")
51
+
52
+ ## Example
53
+ import matplotlib.pyplot as plt
54
+ from py_plt_styler import py_plt_styler
55
+
56
+ # Create sample data
57
+ x = [1, 2, 3, 4, 5]
58
+ y = [1, 4, 9, 16, 25]
59
+
60
+ # Apply the stylesheet BEFORE creating the plot
61
+ py_plt_styler().set_stylesheet("bright").set_font(size=12, weight="bold").apply()
62
+
63
+ # Create a sample plot
64
+ fig, ax = plt.subplots(1,1, figsize=(8, 6))
65
+
66
+ # plot the data using the default parameters for line plots
67
+ lineplot_defaults = py_plt_styler().get_default_parameters("lineplot")
68
+ ax.plot(x, y, **lineplot_defaults)
69
+
70
+ # apply labels and title
71
+ ax.set_title("Sample Plot")
72
+ ax.set_xlabel("X-axis", fontsize=14, fontweight='bold')
73
+ ax.set_ylabel("Y-axis", fontsize=14, fontweight='bold')
74
+
75
+ plt.show()
76
+ ```
@@ -0,0 +1,65 @@
1
+ # py_plt_styler
2
+ A simple package to provide a collection of stylesheets and default values for Python matplotlib figures. The goal is to make it easy to create visually appealing and consistent plots with minimal effort.
3
+
4
+ I will add more stylesheets and default values in the future! If you have any suggestions or want to contribute, feel free to open an issue or a pull request.
5
+
6
+ # Installation
7
+ You can install py_plt_styler using pip:
8
+ ```bash
9
+ pip install py_plt_styler
10
+ ```
11
+
12
+ # Usage
13
+ To use py_plt_styler, simply import the desired stylesheet and apply it to your matplotlib figures. For example:
14
+ ```python
15
+ import matplotlib.pyplot as plt
16
+ from py_plt_styler import py_plt_styler
17
+
18
+ # Apply the default stylesheet
19
+ py_plt_styler().apply()
20
+
21
+ # Apply a predefined stylesheet (e.g., "dark")
22
+ py_plt_styler().set_stylesheet("dark").apply()
23
+
24
+ # Apply a custom stylesheet - must be json (see below for an example)
25
+ py_plt_styler().set_stylesheet("path/to/stylesheet.json").apply()
26
+
27
+ # Change the font
28
+ py_plt_styler().set_font(family="Arial", weight="normal").apply()
29
+
30
+ # Because the py_plt_styler is a singleton and the methods return the instance itself, you can chain the methods together for conveniently readable code:
31
+ py_plt_styler().set_stylesheet("dark").set_font(family="Arial", weight="normal").apply()
32
+
33
+ # The py_plt_styler inclused default parameters for the following plot types:
34
+ # - Line plots
35
+ # - Scatter plots
36
+ # - Box plots
37
+ # - Histograms
38
+
39
+ lineplot_defaults = py_plt_styler().get_default_parameters("lineplot")
40
+
41
+ ## Example
42
+ import matplotlib.pyplot as plt
43
+ from py_plt_styler import py_plt_styler
44
+
45
+ # Create sample data
46
+ x = [1, 2, 3, 4, 5]
47
+ y = [1, 4, 9, 16, 25]
48
+
49
+ # Apply the stylesheet BEFORE creating the plot
50
+ py_plt_styler().set_stylesheet("bright").set_font(size=12, weight="bold").apply()
51
+
52
+ # Create a sample plot
53
+ fig, ax = plt.subplots(1,1, figsize=(8, 6))
54
+
55
+ # plot the data using the default parameters for line plots
56
+ lineplot_defaults = py_plt_styler().get_default_parameters("lineplot")
57
+ ax.plot(x, y, **lineplot_defaults)
58
+
59
+ # apply labels and title
60
+ ax.set_title("Sample Plot")
61
+ ax.set_xlabel("X-axis", fontsize=14, fontweight='bold')
62
+ ax.set_ylabel("Y-axis", fontsize=14, fontweight='bold')
63
+
64
+ plt.show()
65
+ ```
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "py_plt_styler"
3
+ version = "0.0.12"
4
+ description = "A collection of stylesheets and default values for Python matplotlib figures."
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "matplotlib>=3.11.2",
9
+ "numpy>=2.5.5",
10
+ ]
11
+
12
+ [[project.authors]]
13
+ name = "Bela Vogler"
14
+ email = "bela.vogler@uni-jena.de"
15
+
16
+ [project.scripts]
17
+ py_plt_styler = "py_plt_styler:main"
18
+
19
+ [build-system]
20
+ requires = ["uv_build>=0.13.10,<0.14.0"]
21
+ build-backend = "uv_build"
22
+
23
+ [dependency-groups]
24
+ dev = ["ruff>=0.17.6"]
@@ -0,0 +1,25 @@
1
+ [project]
2
+ name = "py_plt_styler"
3
+ version = "0.0.12"
4
+ description = "A collection of stylesheets and default values for Python matplotlib figures."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Bela Vogler", email = "bela.vogler@uni-jena.de" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ dependencies = [
11
+ "matplotlib>=3.11.2",
12
+ "numpy>=2.5.5",
13
+ ]
14
+
15
+ [project.scripts]
16
+ py_plt_styler = "py_plt_styler:main"
17
+
18
+ [build-system]
19
+ requires = ["uv_build>=0.13.10,<0.14.0"]
20
+ build-backend = "uv_build"
21
+
22
+ [dependency-groups]
23
+ dev = [
24
+ "ruff>=0.17.6",
25
+ ]
@@ -0,0 +1,3 @@
1
+ from py_plt_styler.py_plt_styler import py_plt_styler
2
+
3
+ __all__ = ["py_plt_styler"]
@@ -0,0 +1,37 @@
1
+ {
2
+ "widths": 0.5,
3
+ "patch_artist": true,
4
+ "boxprops":
5
+ {
6
+ "facecolor": "lightblue",
7
+ "color": "black", "lw": 2
8
+ },
9
+ "medianprops":
10
+ {
11
+ "color": "black",
12
+ "lw": 1.5
13
+ },
14
+ "meanprops":
15
+ {
16
+ "color": "red",
17
+ "zorder": 3,
18
+ "marker": "D",
19
+ "ms": 10
20
+ },
21
+ "whiskerprops":
22
+ {
23
+ "color": "black",
24
+ "lw": 2
25
+ },
26
+ "capprops":
27
+ {
28
+ "color": "black",
29
+ "lw": 2
30
+ },
31
+ "showfliers": false,
32
+ "showbox": true,
33
+ "showcaps": true,
34
+ "showmeans": true,
35
+ "notch": false,
36
+ "zorder": 0
37
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "alpha": 1.0,
3
+ "edgecolor": "black",
4
+ "color": "lightblue",
5
+ "bins": 30,
6
+ "zorder": 0
7
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "color": "black",
3
+ "linewidth": 2,
4
+ "linestyle": "-",
5
+ "marker": null,
6
+ "markersize": 6,
7
+ "markerfacecolor": "blue",
8
+ "markeredgecolor": "black",
9
+ "markeredgewidth": 1
10
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "s": 10,
3
+ "alpha": 0.7,
4
+ "c": "T",
5
+ "cmap": "magma"
6
+ }
@@ -0,0 +1,383 @@
1
+ ## Dependiencies
2
+ import json
3
+ import logging
4
+ import os
5
+ from typing import Any, NoReturn
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+
10
+
11
+ class py_plt_styler:
12
+ stylesheet: dict[str, Any]
13
+ available_stylesheets: list
14
+ verbose: bool
15
+
16
+ def __init__(
17
+ self, stylesheet: str | dict[str, Any] | None = None, verbose: bool = False
18
+ ) -> "py_plt_styler":
19
+ # set verbosity level for debug output
20
+ self.verbose = verbose
21
+
22
+ # check available stylesheets in the stylesheets directory
23
+ self.available_stylesheets = self.check_available_stylesheets()
24
+
25
+ # check if the provided stylesheet is a string (path to JSON file) or a dictionary, and load it accordingly
26
+ if isinstance(stylesheet, str):
27
+ if stylesheet in self.available_stylesheets:
28
+ # Load the predefined stylesheet
29
+ with open(
30
+ os.path.join(
31
+ os.path.dirname(__file__), "stylesheets", f"{stylesheet}.json"
32
+ ),
33
+ "r",
34
+ ) as f:
35
+ self.stylesheet = json.load(f)
36
+ else:
37
+ # Load the custom stylesheet from the provided path
38
+ with open(stylesheet, "r") as f:
39
+ self.stylesheet = json.load(f)
40
+
41
+ if self.verbose:
42
+ print(f"Stylesheet provided as a string, loaded from {stylesheet}.")
43
+
44
+ elif isinstance(stylesheet, dict):
45
+ self.stylesheet = stylesheet
46
+ if self.verbose:
47
+ print("Stylesheet provided as a dictionary, using provided settings.")
48
+
49
+ else:
50
+ self.stylesheet = {
51
+ "style": "default",
52
+ "font": {"family": "DejaVu Sans", "weight": "bold", "size": 12},
53
+ }
54
+
55
+ if self.verbose:
56
+ print("No stylesheet provided, using default settings.")
57
+
58
+ self.__post_init__()
59
+
60
+ def __post_init__(self):
61
+ # disable matplotlib font manager logging to avoid cluttering the output with warnings about missing fonts
62
+ logging.getLogger("matplotlib.font_manager").disabled = True
63
+
64
+ # apply the stylesheet (style and font settings) to matplotlib
65
+ self.apply()
66
+
67
+ # %% Singleton pattern implementation
68
+ def __new__(cls):
69
+ if not hasattr(cls, "inst"):
70
+ cls.inst = super().__new__(cls)
71
+ return cls.inst
72
+
73
+ # %% Colorbar styling method
74
+ def make_colormap(
75
+ self,
76
+ data: list[int | float] | np.ndarray,
77
+ cmap: str = "viridis",
78
+ normalize: bool = True,
79
+ ) -> plt.cm.ScalarMappable:
80
+ """Create a scalar mappable for a colorbar based on the provided data and colormap. The scalar mappable can be normalized based on the minimum and maximum values of the data.
81
+
82
+ Args:
83
+ data (Union[List[Union[int, float]], np.ndarray]): Iterable data for which the color axis will be created. This can be a list, numpy array, pandas Series, etc.
84
+ cmap (str, optional): The colormap to use. Defaults to "viridis".
85
+ normalize (bool, optional): Whether to normalize the color axis based on the data's minimum and maximum values. Defaults to True.
86
+
87
+ Returns:
88
+ plt.cm.ScalarMappable: The scalar mappable for the colorbar.
89
+ """
90
+ # Convert data to numpy array if it's a list to ensure compatibility with matplotlib's normalization and colormap functions
91
+ if isinstance(data, list):
92
+ data = np.array(data)
93
+
94
+ norm = plt.Normalize(vmin=data.min(), vmax=data.max()) if normalize else None
95
+ sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
96
+ sm.set_array([])
97
+ return sm
98
+
99
+ def make_colorbar(
100
+ self,
101
+ data: list[int | float] | np.ndarray,
102
+ ax: plt.Axes,
103
+ cmap: str = "viridis",
104
+ label: str = "Colorbar",
105
+ fontsize: int = 12,
106
+ fontweight: str = "bold",
107
+ ) -> plt.colorbar:
108
+ """Create a matplotlib colorbar object based on the provided data and colormap, and set the label with the specified font properties.
109
+
110
+ Args:
111
+ data (Union[List[Union[int, float]], np.ndarray]): Iterable data for which the colorbar will be created. This can be a list, numpy array, pandas Series, etc.
112
+ cmap (str, optional): The colormap to use. Defaults to "viridis".
113
+ label (str, optional): The label for the colorbar. Defaults to "Colorbar".
114
+ fontsize (int, optional): The font size for the colorbar label. Defaults to 12.
115
+ fontweight (str, optional): The font weight for the colorbar label. Defaults to "bold".
116
+
117
+ Returns:
118
+ plt.colorbar: The created colorbar object.
119
+ """
120
+ cbar = plt.colorbar(self.make_colormap(data, cmap=cmap), ax=ax)
121
+ cbar.set_label(label, fontsize=fontsize, fontweight=fontweight)
122
+ return cbar
123
+
124
+ def make_color_and_colorbar(
125
+ self,
126
+ data: list[int | float] | np.ndarray,
127
+ ax: plt.Axes,
128
+ cmap: str = "viridis",
129
+ alpha: float = 1.0,
130
+ label: str = "Colorbar",
131
+ fontsize: int = 12,
132
+ fontweight: str = "bold",
133
+ ) -> tuple[np.ndarray, plt.colorbar]:
134
+ """Create a scalar mappable and a colorbar object based on the provided data and colormap.
135
+
136
+ Args:
137
+ data (Union[List[Union[int, float]], np.ndarray]): Iterable data for which the colorbar will be created.
138
+ ax (plt.Axes): The axes on which to place the colorbar.
139
+ cmap (str, optional): The colormap to use. Defaults to "viridis".
140
+ label (str, optional): The label for the colorbar. Defaults to "Colorbar".
141
+ fontsize (int, optional): The font size for the colorbar label. Defaults to 12.
142
+ fontweight (str, optional): The font weight for the colorbar label. Defaults to "bold".
143
+
144
+ Returns:
145
+ tuple[np.ndarray, plt.colorbar]: The created RGB array and colorbar objects.
146
+ """
147
+ # Convert data to numpy array if it's a list to ensure compatibility with matplotlib's normalization and colormap functions
148
+ if isinstance(data, list):
149
+ data = np.array(data)
150
+
151
+ sm = self.make_colormap(data, cmap=cmap)
152
+ cbar = self.make_colorbar(
153
+ data, ax, cmap=cmap, label=label, fontsize=fontsize, fontweight=fontweight
154
+ )
155
+ return sm.to_rgba(data, alpha=alpha), cbar
156
+
157
+ def make_RGBA(
158
+ self,
159
+ data: list[int | float] | np.ndarray,
160
+ cmap: str = "viridis",
161
+ alpha: float = 1.0,
162
+ normalize: bool = True,
163
+ ) -> np.ndarray:
164
+ """Convert the provided data into an RGB array based on the specified colormap and normalization.
165
+
166
+ Args:
167
+ data (Union[List[Union[int, float]], np.ndarray]): Iterable data to be converted into an RGB array. This can be a list, numpy array, pandas Series, etc.
168
+ cmap (str, optional): The colormap to use for the conversion. Defaults to "viridis".
169
+ alpha (float, optional): The alpha (transparency) value for the RGB array. Defaults to 1.0.
170
+ normalize (bool, optional): Whether to normalize the data based on its minimum and maximum values before applying the colormap. Defaults to True.
171
+
172
+ Returns:
173
+ np.ndarray: An RGBA array representing the input data colored according to the specified colormap.
174
+ """
175
+ # Convert data to numpy array if it's a list to ensure compatibility with matplotlib's normalization and colormap functions
176
+ if isinstance(data, list):
177
+ data = np.array(data)
178
+
179
+ norm = plt.Normalize(vmin=data.min(), vmax=data.max()) if normalize else None
180
+ cmap_func = plt.colormaps[cmap]
181
+ rgba_array = (
182
+ cmap_func(norm(data), alpha=alpha) if norm else cmap_func(data, alpha=alpha)
183
+ )
184
+ return rgba_array
185
+
186
+ def make_RGB(
187
+ self,
188
+ data: list[int | float] | np.ndarray,
189
+ cmap: str = "viridis",
190
+ normalize: bool = True,
191
+ ) -> np.ndarray:
192
+ """Convert the provided data into an RGB array based on the specified colormap and normalization.
193
+
194
+ Args:
195
+ data (Union[List[Union[int, float]], np.ndarray]): Iterable data to be converted into an RGB array. This can be a list, numpy array, pandas Series, etc.
196
+ cmap (str, optional): The colormap to use for the conversion. Defaults to "viridis".
197
+ normalize (bool, optional): Whether to normalize the data based on its minimum and maximum values before applying the colormap. Defaults to True.
198
+
199
+ Returns:
200
+ np.ndarray: An RGB array representing the input data colored according to the specified colormap.
201
+ """
202
+ rgba_array = self.make_RGBA(data, cmap=cmap, normalize=normalize)
203
+ return rgba_array[:, :3] # Extract RGB channels, ignore alpha
204
+
205
+ # %% Default parameters for different plot types
206
+ def get_default_parameters(self, plot_type: str) -> dict[str, Any]:
207
+ """Return the default parameters for a given plot type by loading them from a JSON file in the default_parameters directory.
208
+ The JSON file should be named after the plot type (e.g., lineplot.json for "lineplot") and contain a dictionary of default parameters.
209
+
210
+ Args:
211
+ plot_type (str): The type of plot for which to retrieve default parameters.
212
+
213
+ Raises:
214
+ ValueError: If no default parameters are found for the specified plot type.
215
+
216
+ Returns:
217
+ Dict[str, Any]: The default parameters for the specified plot type.
218
+ """
219
+ default_parameters_dir = os.path.join(
220
+ os.path.dirname(__file__), "default_parameters"
221
+ )
222
+ default_parameters_path = os.path.join(
223
+ default_parameters_dir, f"{plot_type}.json"
224
+ )
225
+
226
+ if os.path.exists(default_parameters_path):
227
+ with open(default_parameters_path, "r") as f:
228
+ default_parameters = json.load(f)
229
+ return default_parameters
230
+ else:
231
+ raise ValueError(
232
+ f"No default parameters found for plot type '{plot_type}'."
233
+ )
234
+
235
+ # %% Stylesheet management methods
236
+ def reset_style(self) -> NoReturn:
237
+ """Reset the matplotlib style to the default settings.
238
+
239
+ Returns:
240
+ NoReturn: This method does not return anything.
241
+ """
242
+ plt.style.use("default")
243
+
244
+ def reset_font(self) -> NoReturn:
245
+ """Reset the matplotlib font settings to the default values (family: DejaVu Sans, weight: bold, size: 12).
246
+
247
+ Returns:
248
+ NoReturn: This method does not return anything.
249
+ """
250
+ plt.rc("font", family="DejaVu Sans", weight="bold", size=12)
251
+
252
+ def check_available_stylesheets(self) -> list[str]:
253
+ """Retrieve a list of available stylesheets by checking the stylesheets directory for JSON files and returning their names without the .json extension.
254
+
255
+ Returns:
256
+ List[str]: A list of available stylesheet names.
257
+ """
258
+ stylesheets_dir = os.path.join(os.path.dirname(__file__), "stylesheets")
259
+ available_stylesheets = [
260
+ f[:-5] for f in os.listdir(stylesheets_dir) if f.endswith(".json")
261
+ ]
262
+ return available_stylesheets
263
+
264
+ def check_available_default_parameters(self) -> list[str]:
265
+ """Check the available default parameters by looking for JSON files in the default_parameters directory and returning their names without the .json extension.
266
+
267
+ Returns:
268
+ List[str]: A list of available default parameter names.
269
+ """
270
+ default_parameters_dir = os.path.join(
271
+ os.path.dirname(__file__), "default_parameters"
272
+ )
273
+ available_default_parameters = [
274
+ f[:-5] for f in os.listdir(default_parameters_dir) if f.endswith(".json")
275
+ ]
276
+ return available_default_parameters
277
+
278
+ def reset_stylesheet(self) -> NoReturn:
279
+ """Reset the stylesheet to the default settings by loading the default stylesheet from the stylesheets directory and applying it to matplotlib.
280
+
281
+ Returns:
282
+ NoReturn: This method does not return anything.
283
+ """
284
+ # load the default stylesheet from the stylesheets directory
285
+ with open(
286
+ os.path.join(os.path.dirname(__file__), "stylesheets/default.json"),
287
+ "r",
288
+ ) as f:
289
+ self.stylesheet = json.load(f)
290
+
291
+ # enforce the default stylesheet
292
+ plt.style.use(self.stylesheet["style"])
293
+ plt.rc("font", **self.stylesheet["font"])
294
+
295
+ # %% Methods to set and apply stylesheets and fonts
296
+ def set_font(
297
+ self, family: str = "DejaVu Sans", weight: str = "bold", size: int = 12
298
+ ) -> "py_plt_styler":
299
+ """Set the font properties in the stylesheet to the specified values for family, weight, and size. This method updates the font settings in the stylesheet dictionary and returns the py_plt_styler instance for method chaining.
300
+
301
+ Args:
302
+ family (str, optional): The font family. Defaults to "DejaVu Sans".
303
+ weight (str, optional): The font weight. Defaults to "bold".
304
+ size (int, optional): The font size. Defaults to 12.
305
+
306
+ Returns:
307
+ py_plt_styler: The py_plt_styler instance for method chaining.
308
+ """
309
+ self.stylesheet["font"]["family"] = family
310
+ self.stylesheet["font"]["weight"] = weight
311
+ self.stylesheet["font"]["size"] = size
312
+
313
+ return self
314
+
315
+ def set_style(self, style: str) -> "py_plt_styler":
316
+ """Set the matplotlib style in the stylesheet to the specified style name. This method updates the style setting in the stylesheet dictionary and returns the py_plt_styler instance for method chaining.
317
+
318
+ Args:
319
+ style (str): The matplotlib style name.
320
+
321
+ Returns:
322
+ py_plt_styler: The py_plt_styler instance for method chaining.
323
+ """
324
+ self.stylesheet["style"] = style
325
+
326
+ return self
327
+
328
+ def set_stylesheet(self, stylesheet: str | dict[str, Any]) -> "py_plt_styler":
329
+ """Set the stylesheet for the py_plt_styler instance by loading it from a specified source.
330
+
331
+ Args:
332
+ stylesheet (Union[str, Dict[str, Any]]): The stylesheet to load. This can be a string representing the name of a predefined stylesheet (e.g., "dark", "bright") or a path to a custom JSON file containing the stylesheet settings, or it can be a dictionary with the stylesheet settings.
333
+
334
+ Raises:
335
+ ValueError: If the provided stylesheet is not a valid string or dictionary.
336
+
337
+ Returns:
338
+ py_plt_styler: The py_plt_styler instance with the updated stylesheet for method chaining.
339
+ """
340
+ # check if the provided stylesheet is a string (path to JSON file) or a dictionary, and load it accordingly
341
+ if isinstance(stylesheet, str):
342
+ if stylesheet in self.available_stylesheets:
343
+ # Load the predefined stylesheet
344
+ with open(
345
+ os.path.join(
346
+ os.path.dirname(__file__), "stylesheets", f"{stylesheet}.json"
347
+ ),
348
+ "r",
349
+ ) as f:
350
+ self.stylesheet = json.load(f)
351
+ else:
352
+ # Load the custom stylesheet from the provided path
353
+ with open(stylesheet, "r") as f:
354
+ self.stylesheet = json.load(f)
355
+
356
+ if self.verbose:
357
+ print(f"Stylesheet provided as a string, loaded from {stylesheet}.")
358
+
359
+ elif isinstance(stylesheet, dict):
360
+ self.stylesheet = stylesheet
361
+ if self.verbose:
362
+ print("Stylesheet provided as a dictionary, using provided settings.")
363
+
364
+ else:
365
+ raise TypeError(
366
+ "Stylesheet must be either a string (path to JSON file) or a dictionary."
367
+ )
368
+
369
+ return self
370
+
371
+ def apply(self) -> NoReturn:
372
+ """Apply the stylesheet (style and font settings) to matplotlib by enforcing both the style and font settings from the stylesheet dictionary.
373
+
374
+ Returns:
375
+ NoReturn: This method does not return anything.
376
+ """
377
+ # reset to default to avoid compounding styles when calling this method multiple times
378
+ self.reset_style()
379
+ self.reset_font()
380
+
381
+ # enforce the stylesheet
382
+ plt.style.use(self.stylesheet["style"])
383
+ plt.rc("font", **self.stylesheet["font"])
@@ -0,0 +1,8 @@
1
+ {
2
+ "style": "seaborn-v0_8-bright",
3
+ "font": {
4
+ "family": "DejaVu Sans",
5
+ "weight": "bold",
6
+ "size": 16
7
+ }
8
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "style": "dark_background",
3
+ "font": {
4
+ "family": "DejaVu Sans",
5
+ "weight": "bold",
6
+ "size": 16
7
+ }
8
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "style": "default",
3
+ "font": {
4
+ "family": "DejaVu Sans",
5
+ "weight": "bold",
6
+ "size": 12
7
+ }
8
+ }