-
Notifications
You must be signed in to change notification settings - Fork 0
/
matplotlib_helper.py
390 lines (338 loc) · 11.5 KB
/
matplotlib_helper.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
"""
https://github.com/kiwi0fruit/matplotlibhelper
"""
import io
import base64
# noinspection PyUnresolvedReferences
from sugartex import sugartex, stex
import numpy as np
from numpy import ndarray as Array
import pandas as pd
from typing import Tuple, Union, Iterable
import os
from os import path as p
from IPython import get_ipython
class F:
KNITTY = 'knitty'
PYTHON = 'python'
NTERACT = 'nteract'
LAB = 'lab'
OTHER = 'other'
def is_notebook_or_qtconsole():
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # IPython Terminal
elif shell == 'NoneType':
return False # Python interpreter
else:
return False
def get_front() -> str:
if not get_ipython():
return F.PYTHON
if os.getenv('KNITTY', '').lower() == 'true':
return F.KNITTY
if is_notebook_or_qtconsole():
path = os.getenv('PATH', '')
atom_win = os.sep + 'atom' + os.sep + 'app-'
atom_lin = os.sep + 'atom' + os.pathsep
nteract_win = os.sep + 'nteract' + os.pathsep
nteract_lin = '_nterac'
if (nteract_win in path) or (nteract_lin in path) or (atom_win in path) or (atom_lin in path):
return F.NTERACT
try:
import jupyterlab
import ipympl
return F.LAB
except ModuleNotFoundError:
pass
return F.OTHER
def import_matplotlib(magic: str or None):
front = get_front()
if magic == 'auto':
if front == F.KNITTY:
magic = "agg"
elif front == F.NTERACT:
magic = "qt5"
elif front == F.LAB:
magic = "widget"
elif front == F.PYTHON:
magic = 'Qt5Agg' # special case
elif (magic == 'qt5') and (front == F.PYTHON):
magic = 'Qt5Agg' # special case
if magic is None:
import matplotlib
elif magic == 'Qt5Agg':
import matplotlib
matplotlib.use('Qt5Agg')
else:
get_ipython().magic("matplotlib " + magic)
import matplotlib
_readied = False
GR = (1 + 5 ** 0.5) / 2
sugartex.mpl_hack()
sugartex.ready()
# noinspection PyIncorrectDocstring
def ready(ext: str='svg',
dpi: int=300,
folder: str='./pic',
hide: bool=False,
magic: str='auto',
font_dir: str=None,
font_size: float=12.8,
font_family: str="serif",
font_serif: Union[str, Tuple[str, ...]]=('STIX Two Text', 'STIX Two Math'),
font_sans: Union[str, Tuple[str, ...]]=('Segoe UI', 'Noto Sans', 'DejaVu Sans'),
font_cursive: Union[str, Tuple[str, ...]]=None,
font_mono: Union[str, Tuple[str, ...]]=('Robotization Mono', 'DejaVu Sans Mono'),
fontm_set: str='custom',
fontm_mono: str='Robotization Mono',
fontm_calig: str="MJ_Cal",
fontm_regular: str="MJ",
fontm_italic: str="MJ_Mat",
fontm_bold: str="MJ",
fontm_itbold: str="MJ_Mat",
):
"""
Should be run before ``import matplotlib.pyplot``.
``magic`` auto-detect for ``f'%matplotlib {magic}'`` (if ``'auto'``):
* In Knitty mode uses ``agg`` (if ``$KNITTY`` env var is ``TRUE``),
* In JupyterLab mode uses ``widget``
(if ``jupyterlab`` and ``ipympl`` modules were found),
* In Hydrogen and Nteract modes uses ``qt5`` magic,
* In non-Jupyter and non-IPython modes calls ``matplotlib.use('Qt5Agg')``.
Parameters
----------
folder :
folder to save images to.
magic :
matplotlib magic without "%matplotlib " prefix
or None for not changing matplotlib backend
("qt5" magic can work even without IPython/Jupyter).
font_size :
In pt. Default is 12.8pt ~ 17px.
fontm_set :
'cm' is also a good option.
"""
# Set mpl backend:
# ----------------
import_matplotlib(magic)
import matplotlib as mpl
from matplotlib import font_manager
# Set mpl fonts:
# ----------------------
def list_maybe(fonts: Union[str, Iterable]):
return fonts if isinstance(fonts, str) else list(fonts)
mpl.rcParams.update({
"text.usetex": False,
"font.size": font_size,
"font.family": font_family,
"font.serif": list_maybe(font_serif),
"font.sans-serif": list_maybe(font_sans),
"font.monospace": list_maybe(font_mono),
"mathtext.fontset": fontm_set,
"mathtext.cal": fontm_calig,
"mathtext.tt": fontm_mono,
"mathtext.rm": fontm_regular,
"mathtext.it": fontm_italic + ":italic",
"mathtext.bf": fontm_bold + ":bold",
"mathtext.sf": fontm_itbold + ":bold:italic",
})
if font_cursive is not None:
mpl.rcParams["font.cursive"] = list_maybe(font_cursive)
if mpl.__version__.startswith('2'):
mpl.rc('text.latex', unicode=True)
font_dirs = [p.join(p.dirname(__file__), 'fonts')]
if font_dir is not None:
font_dirs.append(font_dir)
font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
font_list = font_manager.createFontList(font_files)
font_manager.fontManager.ttflist.extend(font_list)
# Create prefix folder if needed:
# -------------------------------
if folder != '':
folder = p.normpath(p.expanduser(p.expandvars(folder)))
if not p.isdir(folder):
os.makedirs(folder)
# Export globals:
# ---------------
global _ext, _dpi, _hide, _folder, _readied
_ext, _dpi, _hide, _folder, _readied = ext, dpi, hide, folder, True
def img(name: str=None,
ext: str=None,
dpi: int=None,
hide: bool=None,
return_path: bool=False
) -> str:
"""
* If ``name`` is ``None`` then do not save an image.
* If ``name`` is a relative path then it's relative
with respect to the ``folder`` if it was specified
in ``ready()`` otherwise - to the CWD.
Parameters
----------
name :
File name to store image (without extension).
ext :
File extension (or base64 format).
[Default is 'svg' or the value set in `ready()`]
dpi :
DPI for PNG
[Default is 300 or the value set in `ready()`]
hide :
Whether to hide interactive plot via Qt or Widget or not.
[Default is False or the value set in `ready()`]
return_path :
Whether to return file path instead of base64 if `name` was given
Returns
------
url :
Image base64 URL (or file path if `return_path`).
"""
if not _readied:
ready()
import matplotlib as mpl
import matplotlib.pyplot as plot
ext = ext if (ext is not None) else _ext
dpi = dpi if (dpi is not None) else _dpi
hide = hide if (hide is not None) else _hide
if name:
file = p.normpath(p.expanduser(p.expandvars(name + "." + ext)))
file = file if p.isabs(file) else p.normpath(p.join(_folder, file))
if ext.upper() == 'PNG':
plot.savefig(file, dpi=dpi)
else:
plot.savefig(file)
with open(file, "rb") as f:
image = f.read()
if not p.abspath(file):
file = file.replace('\\', '/')
else:
file = None
with io.BytesIO() as f:
plot.savefig(f, format=ext)
image = f.getvalue()
base64_url = 'data:image/{};base64,' + base64.b64encode(image).decode("utf-8")
if ext.upper() == 'PNG':
base64_url = base64_url.format('png')
elif ext.upper() == 'SVG':
base64_url = base64_url.format('svg+xml')
else:
raise ValueError(f'{ext} extension is not supported by matplotlib helper.')
if hide:
plot.close() # works in Jupyter too
elif mpl.get_backend() != 'agg':
plot.show()
if return_path and name:
return file
else:
return base64_url
def img_path(name: str,
ext: str=None,
dpi: int=None,
hide: bool=None,
) -> str:
"""
If ``name`` is a relative path then it's relative
with respect to the ``folder`` if it was specified
in ``ready()`` otherwise - to the CWD.
Parameters
----------
name :
File name to store image (without extension).
ext :
File extension (or base64 format).
[Default is 'svg' or the value set in `ready()`]
dpi :
DPI for PNG
[Default is 300 or the value set in `ready()`]
hide :
Whether to hide interactive plot via Qt or Widget or not.
[Default is False or the value set in `ready()`]
Returns
------
url :
Image path
"""
if not (name and isinstance(name, str)):
raise ValueError(f"Invalid name: '{name}'")
return img(name, ext, dpi, hide, return_path=True)
# noinspection PyPep8Naming
def dump2D(file_path: str,
matrix: Array=None,
x: Array=None,
y: Array=None,
stack: Tuple[Array, ...]=None,
cat: Tuple[Array, ...]=None,
header=False) -> None:
"""
Dumps 2D plot arguments to CSV file. Provide 2D matrix,
or two 1D arrays, or tuple of 1D or 2D arrays.
Parameters
----------
file_path :
matrix :
2D array [[x, y, ...], ...]
x :
1D array
y :
1D array
stack :
tuple of 1D arrays
cat :
tuple of 1D or 2D arrays
header :
boolean or list of string, default True
Write out the column names. If a list of strings is given
it is assumed to be aliases for the column names
"""
if not (matrix is None):
pass
elif not (x is None) and not (y is None):
matrix = np.stack((x, y), axis=-1)
elif not (stack is None):
matrix = np.stack(stack, axis=-1)
elif not (cat is None):
matrix = np.concatenate([arr if len(arr.shape) > 1 else arr[np.newaxis].T
for arr in cat], axis=-1)
else:
raise ValueError('Neither matrix, nor x,y, nor stack, nor cat were provided.')
pd.DataFrame(matrix).to_csv(file_path, header=header, index=None)
# noinspection PyShadowingNames
def inch(cm: float=None, mm: float=None) -> float:
""" Either cm or mm to inch """
if (cm is not None) and (mm is None):
return cm / 2.54
elif (mm is not None) and (cm is None):
return (mm / 10) / 2.54
else:
raise ValueError('Either cm or mm should be provided.')
# noinspection PyShadowingNames
def cm(inch: float) -> float:
""" inch to cm """
return inch * 2.54
# noinspection PyShadowingNames
def mm(inch: float) -> float:
""" inch to mm """
return (inch * 2.54) * 10
def figsize(w: float=None, h: float=None) -> Tuple[float, float]:
"""
Returns (width, height) based on golden ratio
if either width or height was provided.
If both specified then they are simply returned.
"""
if (w is None) and (h is None):
raise ValueError('Either width or height should be provided.')
w = (h * GR) if (w is None) else w
h = (w / GR) if (h is None) else h
return w, h
# http://blog.alivate.com.au/poppler-windows/
# import subprocess.call
# import os
# _poppler = ""
# poppler: str=r'C:\Program Files (x86)\poppler\bin',
# global _poppler; _poppler = poppler
# plot.savefig(name + ".pdf") # was useful with external LaTeX renderer instead of matplotlib's
# subprocess.call([os.path.join(_poppler, "pdftocairo"), "-svg", name + ".pdf", name + ".svg"],
# cwd=os.getcwd())