-
Notifications
You must be signed in to change notification settings - Fork 49
/
subplots.py
317 lines (270 loc) · 10.8 KB
/
subplots.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
#
# Copyright (c) 2019. JetBrains s.r.o.
# Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#
# noinspection PyUnresolvedReferences
from typing import Dict
from lets_plot.plot.core import DummySpec
from lets_plot.plot.core import FeatureSpec
from lets_plot.plot.core import FeatureSpecArray
from lets_plot.plot.core import _specs_to_dict
from lets_plot.plot.core import _theme_dicts_merge
from lets_plot.plot.core import _to_svg, _to_html, _export_as_raster
__all__ = ['SupPlotsSpec']
class SupPlotsLayoutSpec:
"""
Plots layout specification used in constructing subplots figure.
"""
def __init__(self, name: str, **kwargs):
"""Initialize self."""
self.__props = {}
self.__props.update(**kwargs)
self.__props['name'] = name
def as_dict(self) -> Dict:
return _specs_to_dict(self.__props)
class SupPlotsSpec(FeatureSpec):
"""
Subplots figure specification.
See: `gggrid()`
"""
@classmethod
def duplicate(cls, other):
dup = SupPlotsSpec(
figures=other.__figures,
layout=other.__layout
)
dup.props().update(other.props())
return dup
def __init__(self, figures: list, layout: SupPlotsLayoutSpec):
"""Initialize self."""
super().__init__('subplots', None)
self.__figures = list(figures)
self.__layout = layout
def __add__(self, other):
"""
"""
if isinstance(other, DummySpec):
# nothing
return self
elif isinstance(other, FeatureSpecArray):
supplots = SupPlotsSpec.duplicate(self)
for spec in other.elements():
supplots = supplots.__add__(spec)
return supplots
elif isinstance(other, FeatureSpec) and other.kind in ["ggsize", "theme"]:
supplots = SupPlotsSpec.duplicate(self)
# ToDo: duplication!
if other.kind == 'theme':
new_theme_options = {k: v for k, v in other.props().items() if v is not None}
if 'name' in new_theme_options:
# keep the previously specified flavor
if supplots.props().get('theme', {}).get('flavor', None) is not None:
new_theme_options.update({'flavor': supplots.props()['theme']['flavor']})
# pre-configured theme overrides existing theme altogether.
supplots.props()['theme'] = new_theme_options
else:
# merge themes
old_theme_options = supplots.props().get('theme', {})
supplots.props()['theme'] = _theme_dicts_merge(old_theme_options, new_theme_options)
return supplots
# add feature to properties
supplots.props()[other.kind] = other
return supplots
return super().__add__(other)
def as_dict(self):
d = super().as_dict()
d['kind'] = self.kind
d['layout'] = self.__layout.as_dict()
d['figures'] = [figure.as_dict() if figure is not None else None for figure in self.__figures]
return d
def _repr_html_(self):
"""
Special method discovered and invoked by IPython.display.display.
"""
from ..frontend_context._configuration import _as_html
return _as_html(self.as_dict())
def show(self):
"""
Draw all plots currently in this 'bunch'.
"""
from ..frontend_context._configuration import _display_plot
_display_plot(self)
def to_svg(self, path) -> str:
"""
Export all plots currently in this 'bunch' to a file or file-like object in SVG format.
Parameters
----------
self : `SupPlotsSpec`
Subplots specification to export.
path : str, file-like object
Сan be either a string specifying a file path or a file-like object.
If a string is provided, the result will be exported to the file at that path.
If a file-like object is provided, the result will be exported to that object.
Returns
-------
str
Absolute pathname of created file or None if file-like object is provided.
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 13
import numpy as np
import io
import os
from lets_plot import *
from IPython import display
LetsPlot.setup_html()
n = 60
np.random.seed(42)
x = np.random.choice(list('abcde'), size=n)
y = np.random.normal(size=n)
p = ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + geom_jitter()
file_like = io.BytesIO()
p.to_svg(file_like)
display.SVG(file_like.getvalue())
"""
return _to_svg(self, path)
def to_html(self, path, iframe: bool = None) -> str:
"""
Export all plots currently in this 'bunch' to a file or file-like object in HTML format.
Parameters
----------
self : `SupPlotsSpec`
Subplots specification to export.
path : str, file-like object
Сan be either a string specifying a file path or a file-like object.
If a string is provided, the result will be exported to the file at that path.
If a file-like object is provided, the result will be exported to that object.
iframe : bool, default=False
Whether to wrap HTML page into a iFrame.
Returns
-------
str
Absolute pathname of created file or None if file-like object is provided.
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 12
import numpy as np
import io
import os
from lets_plot import *
LetsPlot.setup_html()
n = 60
np.random.seed(42)
x = np.random.choice(list('abcde'), size=n)
y = np.random.normal(size=n)
p = ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + geom_jitter()
file_like = io.BytesIO()
p.to_html(file_like)
"""
return _to_html(self, path, iframe)
def to_png(self, path, scale=None, w=None, h=None, unit=None, dpi=None) -> str:
"""
Export all plots currently in this 'bunch' to a file or file-like object in PNG format.
Parameters
----------
self : `SupPlotsSpec`
Subplots specification to export.
path : str, file-like object
Сan be either a string specifying a file path or a file-like object.
If a string is provided, the result will be exported to the file at that path.
If a file-like object is provided, the result will be exported to that object.
scale : float
Scaling factor for raster output. Default value is 2.0.
w : float, default=None
Only applicable when exporting to PNG or PDF.
h : float, default=None
Height of the output image in units.
Only applicable when exporting to PNG or PDF.
unit : {'in', 'cm', 'mm'}, default=None
Unit of the output image. One of: 'in', 'cm', 'mm'.
Only applicable when exporting to PNG or PDF.
dpi : int, default=None
Resolution in dots per inch.
Only applicable when exporting to PNG or PDF.
Returns
-------
str
Absolute pathname of created file or None if file-like object is provided.
Notes
-----
Export to PNG file uses the CairoSVG library.
CairoSVG is free and distributed under the LGPL-3.0 license.
For more details visit: https://cairosvg.org/documentation/
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 13
import numpy as np
import io
import os
from lets_plot import *
from IPython import display
LetsPlot.setup_html()
n = 60
np.random.seed(42)
x = np.random.choice(list('abcde'), size=n)
y = np.random.normal(size=n)
p = ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + geom_jitter()
file_like = io.BytesIO()
p.to_png(file_like)
display.Image(file_like.getvalue())
"""
return _export_as_raster(self, path, scale, 'png', w=w, h=h, unit=unit, dpi=dpi)
def to_pdf(self, path, scale=None, w=None, h=None, unit=None, dpi=None) -> str:
"""
Export all plots currently in this 'bunch' to a file or file-like object in PDF format.
Parameters
----------
self : `SupPlotsSpec`
Subplots specification to export.
path : str, file-like object
Сan be either a string specifying a file path or a file-like object.
If a string is provided, the result will be exported to the file at that path.
If a file-like object is provided, the result will be exported to that object.
scale : float
Scaling factor for raster output. Default value is 2.0.
w : float, default=None
Width of the output image in units.
Only applicable when exporting to PNG or PDF.
h : float, default=None
Height of the output image in units.
Only applicable when exporting to PNG or PDF.
unit : {'in', 'cm', 'mm'}, default=None
Unit of the output image. One of: 'in', 'cm', 'mm'.
Only applicable when exporting to PNG or PDF.
dpi : int, default=None
Resolution in dots per inch.
Only applicable when exporting to PNG or PDF.
Returns
-------
str
Absolute pathname of created file or None if file-like object is provided.
Notes
-----
Export to PDF file uses the CairoSVG library.
CairoSVG is free and distributed under the LGPL-3.0 license.
For more details visit: https://cairosvg.org/documentation/
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 12
import numpy as np
import io
import os
from lets_plot import *
LetsPlot.setup_html()
n = 60
np.random.seed(42)
x = np.random.choice(list('abcde'), size=n)
y = np.random.normal(size=n)
p = ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + geom_jitter()
file_like = io.BytesIO()
p.to_pdf(file_like)
"""
return _export_as_raster(self, path, scale, 'pdf', w=w, h=h, unit=unit, dpi=dpi)