lets-plot 4.6.0rc1__cp39-cp39-macosx_10_15_x86_64.whl

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.

Potentially problematic release.


This version of lets-plot might be problematic. Click here for more details.

Files changed (91) hide show
  1. lets_plot/__init__.py +283 -0
  2. lets_plot/_global_settings.py +191 -0
  3. lets_plot/_kbridge.py +134 -0
  4. lets_plot/_type_utils.py +110 -0
  5. lets_plot/_version.py +6 -0
  6. lets_plot/bistro/__init__.py +16 -0
  7. lets_plot/bistro/_plot2d_common.py +100 -0
  8. lets_plot/bistro/corr.py +447 -0
  9. lets_plot/bistro/im.py +196 -0
  10. lets_plot/bistro/joint.py +192 -0
  11. lets_plot/bistro/qq.py +207 -0
  12. lets_plot/bistro/residual.py +341 -0
  13. lets_plot/bistro/waterfall.py +252 -0
  14. lets_plot/export/__init__.py +6 -0
  15. lets_plot/export/ggsave_.py +133 -0
  16. lets_plot/frontend_context/__init__.py +8 -0
  17. lets_plot/frontend_context/_configuration.py +144 -0
  18. lets_plot/frontend_context/_frontend_ctx.py +16 -0
  19. lets_plot/frontend_context/_html_contexts.py +117 -0
  20. lets_plot/frontend_context/_intellij_python_json_ctx.py +38 -0
  21. lets_plot/frontend_context/_json_contexts.py +39 -0
  22. lets_plot/frontend_context/_jupyter_notebook_ctx.py +119 -0
  23. lets_plot/frontend_context/_mime_types.py +7 -0
  24. lets_plot/frontend_context/_static_html_page_ctx.py +27 -0
  25. lets_plot/frontend_context/_static_svg_ctx.py +26 -0
  26. lets_plot/frontend_context/_webbr_html_page_ctx.py +29 -0
  27. lets_plot/frontend_context/sandbox.py +5 -0
  28. lets_plot/geo_data/__init__.py +18 -0
  29. lets_plot/geo_data/core.py +331 -0
  30. lets_plot/geo_data/geocoder.py +977 -0
  31. lets_plot/geo_data/geocodes.py +512 -0
  32. lets_plot/geo_data/gis/__init__.py +0 -0
  33. lets_plot/geo_data/gis/fluent_dict.py +201 -0
  34. lets_plot/geo_data/gis/geocoding_service.py +42 -0
  35. lets_plot/geo_data/gis/geometry.py +91 -0
  36. lets_plot/geo_data/gis/json_request.py +232 -0
  37. lets_plot/geo_data/gis/json_response.py +308 -0
  38. lets_plot/geo_data/gis/request.py +492 -0
  39. lets_plot/geo_data/gis/response.py +247 -0
  40. lets_plot/geo_data/livemap_helper.py +65 -0
  41. lets_plot/geo_data/to_geo_data_frame.py +141 -0
  42. lets_plot/geo_data/type_assertion.py +34 -0
  43. lets_plot/geo_data_internals/__init__.py +4 -0
  44. lets_plot/geo_data_internals/constants.py +13 -0
  45. lets_plot/geo_data_internals/utils.py +33 -0
  46. lets_plot/mapping.py +115 -0
  47. lets_plot/package_data/lets-plot.min.js +2 -0
  48. lets_plot/plot/__init__.py +64 -0
  49. lets_plot/plot/_global_theme.py +14 -0
  50. lets_plot/plot/annotation.py +233 -0
  51. lets_plot/plot/coord.py +242 -0
  52. lets_plot/plot/core.py +943 -0
  53. lets_plot/plot/expand_limits_.py +78 -0
  54. lets_plot/plot/facet.py +206 -0
  55. lets_plot/plot/font_features.py +71 -0
  56. lets_plot/plot/geom.py +8160 -0
  57. lets_plot/plot/geom_extras.py +53 -0
  58. lets_plot/plot/geom_function_.py +216 -0
  59. lets_plot/plot/geom_imshow_.py +401 -0
  60. lets_plot/plot/geom_livemap_.py +330 -0
  61. lets_plot/plot/ggbunch_.py +96 -0
  62. lets_plot/plot/gggrid_.py +126 -0
  63. lets_plot/plot/ggtb_.py +56 -0
  64. lets_plot/plot/guide.py +229 -0
  65. lets_plot/plot/label.py +187 -0
  66. lets_plot/plot/marginal_layer.py +181 -0
  67. lets_plot/plot/plot.py +244 -0
  68. lets_plot/plot/pos.py +346 -0
  69. lets_plot/plot/sampling.py +338 -0
  70. lets_plot/plot/sandbox_.py +26 -0
  71. lets_plot/plot/scale.py +3577 -0
  72. lets_plot/plot/scale_colormap_mpl.py +297 -0
  73. lets_plot/plot/scale_convenience.py +155 -0
  74. lets_plot/plot/scale_identity_.py +658 -0
  75. lets_plot/plot/scale_position.py +1336 -0
  76. lets_plot/plot/series_meta.py +129 -0
  77. lets_plot/plot/stat.py +581 -0
  78. lets_plot/plot/subplots.py +322 -0
  79. lets_plot/plot/subplots_util.py +24 -0
  80. lets_plot/plot/theme_.py +766 -0
  81. lets_plot/plot/theme_set.py +393 -0
  82. lets_plot/plot/tooltip.py +486 -0
  83. lets_plot/plot/util.py +226 -0
  84. lets_plot/settings_utils.py +244 -0
  85. lets_plot/tilesets.py +364 -0
  86. lets_plot-4.6.0rc1.dist-info/LICENSE +21 -0
  87. lets_plot-4.6.0rc1.dist-info/METADATA +199 -0
  88. lets_plot-4.6.0rc1.dist-info/RECORD +91 -0
  89. lets_plot-4.6.0rc1.dist-info/WHEEL +5 -0
  90. lets_plot-4.6.0rc1.dist-info/top_level.txt +2 -0
  91. lets_plot_kotlin_bridge.cpython-39-darwin.so +0 -0
lets_plot/plot/core.py ADDED
@@ -0,0 +1,943 @@
1
+ #
2
+ # Copyright (c) 2019. JetBrains s.r.o.
3
+ # Use of this source code is governed by the MIT license that can be found in the LICENSE file.
4
+ #
5
+ import io
6
+ import json
7
+ import os
8
+ from typing import Union
9
+
10
+ __all__ = ['aes', 'layer']
11
+
12
+ from lets_plot._global_settings import get_global_bool, has_global_value, FRAGMENTS_ENABLED
13
+
14
+
15
+ def aes(x=None, y=None, **kwargs):
16
+ """
17
+ Define aesthetic mappings.
18
+
19
+ Parameters
20
+ ----------
21
+ x, y, ... :
22
+ List of name value pairs giving aesthetics to map to variables.
23
+ The names for x and y aesthetics are typically omitted because they are so common; all other aesthetics must be named.
24
+
25
+ Returns
26
+ -------
27
+ `FeatureSpec`
28
+ Aesthetic mapping specification.
29
+
30
+ Notes
31
+ -----
32
+ Generate aesthetic mappings that describe how variables in the data are projected to visual properties
33
+ (aesthetics) of geometries. This function also standardizes aesthetic names by, for example, converting
34
+ colour to color.
35
+
36
+ Aesthetic mappings are not to be confused with aesthetic settings; the latter are used to set aesthetics to
37
+ some constant values, e.g. make all points red in the plot. If one wants to make the color of a point
38
+ depend on the value of a variable, he/she should project this variable to the color aesthetic via
39
+ aesthetic mapping.
40
+
41
+ Examples
42
+ --------
43
+ .. jupyter-execute::
44
+ :linenos:
45
+ :emphasize-lines: 10-11
46
+
47
+ import numpy as np
48
+ from lets_plot import *
49
+ LetsPlot.setup_html()
50
+ n = 100
51
+ np.random.seed(42)
52
+ x = np.random.uniform(-1, 1, size=n)
53
+ y = 25 * x ** 2 + np.random.normal(size=n)
54
+ c = np.where(x < 0, '0', '1')
55
+ ggplot({'x': x, 'y': y, 'c': c}) + \\
56
+ geom_point(aes('x', 'y', color='y', shape='c', size='x')) + \\
57
+ geom_smooth(aes(x='x', y='y'), deg=2, size=1)
58
+
59
+ |
60
+
61
+ .. jupyter-execute::
62
+ :linenos:
63
+ :emphasize-lines: 3-4
64
+
65
+ from lets_plot import *
66
+ LetsPlot.setup_html()
67
+ ggplot() + geom_polygon(aes(x=[0, 1, 2], y=[2, 1, 4]), \\
68
+ color='black', alpha=.5, size=1)
69
+
70
+ """
71
+
72
+ return FeatureSpec('mapping', name=None, x=x, y=y, **kwargs)
73
+
74
+
75
+ def layer(geom=None, stat=None, data=None, mapping=None, position=None, **kwargs):
76
+ """
77
+ Create a new layer.
78
+
79
+ Parameters
80
+ ----------
81
+ geom : str
82
+ The geometric object to use to display the data.
83
+ stat : str, default='identity'
84
+ The statistical transformation to use on the data for this layer, as a string.
85
+ Supported transformations: 'identity' (leaves the data unchanged),
86
+ 'count' (count number of points with same x-axis coordinate),
87
+ 'bin' (count number of points with x-axis coordinate in the same bin),
88
+ 'smooth' (perform smoothing - linear default),
89
+ 'density' (compute and draw kernel density estimate).
90
+ data : dict or Pandas or Polars `DataFrame`
91
+ The data to be displayed in this layer. If None, the default, the data
92
+ is inherited from the plot data as specified in the call to ggplot.
93
+ mapping : `FeatureSpec`
94
+ Set of aesthetic mappings created by `aes()` function.
95
+ Aesthetic mappings describe the way that variables in the data are
96
+ mapped to plot "aesthetics".
97
+ position : str or `FeatureSpec`
98
+ Position adjustment.
99
+ Either a position adjustment name: 'dodge', 'dodgev', 'jitter', 'nudge', 'jitterdodge', 'fill',
100
+ 'stack' or 'identity', or the result of calling a position adjustment function (e.g., `position_dodge()` etc.).
101
+ kwargs:
102
+ Other arguments passed on to layer. These are often aesthetics settings, used to set an aesthetic to a fixed
103
+ value, like color = "red", fill = "blue", size = 3 or shape = 21. They may also be parameters to the
104
+ paired geom/stat.
105
+
106
+ Returns
107
+ -------
108
+ `LayerSpec`
109
+ Geom object specification.
110
+
111
+ Notes
112
+ -----
113
+ A layer is a combination of data, stat and geom with a potential position adjustment. Usually layers are created
114
+ using geom_* or stat_* calls but they can be created directly using this function.
115
+
116
+ Examples
117
+ --------
118
+ .. jupyter-execute::
119
+ :linenos:
120
+ :emphasize-lines: 8
121
+
122
+ import numpy as np
123
+ from lets_plot import *
124
+ LetsPlot.setup_html()
125
+ n = 50
126
+ np.random.seed(42)
127
+ x = np.random.uniform(-1, 1, size=n)
128
+ y = 25 * x ** 2 + np.random.normal(size=n)
129
+ ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + layer(geom='point')
130
+
131
+ """
132
+ # todo: other parameters: inherit.aes = TRUE, subset = NULL, show.legend = NA
133
+
134
+ return LayerSpec(**locals())
135
+
136
+
137
+ def _filter_none(original: dict) -> dict:
138
+ return {k: v for k, v in original.items() if v is not None}
139
+
140
+
141
+ #
142
+ # -----------------------------------
143
+ # Specs
144
+ #
145
+
146
+ def _specs_to_dict(opts_raw):
147
+ opts = {}
148
+ for k, v in opts_raw.items():
149
+ if isinstance(v, FeatureSpec):
150
+ opts[k] = v.as_dict()
151
+ elif isinstance(v, dict):
152
+ opts[k] = _specs_to_dict(v)
153
+ else:
154
+ opts[k] = v
155
+
156
+ return _filter_none(opts)
157
+
158
+
159
+ class FeatureSpec():
160
+ """
161
+ A base class of the plot objects.
162
+
163
+ Do not use this class explicitly.
164
+
165
+ Instead, you should construct its objects with functions `ggplot()`, `geom_point()`,
166
+ `position_dodge()`, `scale_x_continuous()` etc.
167
+ """
168
+
169
+ def __init__(self, kind, name, **kwargs):
170
+ """Initialize self."""
171
+ self.kind = kind
172
+ self.__props = {}
173
+ if name is not None:
174
+ self.__props['name'] = name
175
+ self.__props.update(**kwargs)
176
+
177
+ def props(self):
178
+ return self.__props
179
+
180
+ def as_dict(self):
181
+ """
182
+ Return the dictionary of all properties of the object with `as_dict()`
183
+ applied recursively to all subproperties of `FeatureSpec` type.
184
+
185
+ Returns
186
+ -------
187
+ dict
188
+ Dictionary of properties.
189
+
190
+ Examples
191
+ --------
192
+ .. jupyter-execute::
193
+ :linenos:
194
+ :emphasize-lines: 4
195
+
196
+ from lets_plot import *
197
+ LetsPlot.setup_html()
198
+ p = ggplot({'x': [0], 'y': [0]}) + geom_point(aes('x', 'y'))
199
+ p.as_dict()
200
+ """
201
+ return _specs_to_dict(self.props())
202
+
203
+ def __str__(self):
204
+ return json.dumps(self.as_dict(), indent=2)
205
+
206
+ def __add__(self, other):
207
+ if isinstance(other, DummySpec):
208
+ # nothing
209
+ return self
210
+
211
+ if self.kind in ["plot", "subplots"]:
212
+ # pass and fail: don't allow to add plot to a feature list.
213
+ pass
214
+ elif isinstance(other, FeatureSpec):
215
+ if other.kind in ["plot", "subplots"]:
216
+ # pass and fail: don't allow to add plot to a feature list.
217
+ pass
218
+ else:
219
+ arr = FeatureSpecArray(self, other)
220
+ return arr
221
+
222
+ raise TypeError('unsupported operand type(s) for +: {} and {}'
223
+ .format(self.__class__, other.__class__))
224
+
225
+
226
+ class PlotSpec(FeatureSpec):
227
+ """
228
+ A class of the initial plot object.
229
+
230
+ Do not use this class explicitly.
231
+
232
+ Instead, you should construct its objects with functions `ggplot()`,
233
+ `corr_plot(...).points().build()` etc.
234
+ """
235
+
236
+ @classmethod
237
+ def duplicate(cls, other):
238
+ dup = PlotSpec(data=None, mapping=None,
239
+ scales=other.__scales,
240
+ layers=other.__layers,
241
+ metainfo_list=other.__metainfo_list,
242
+ is_livemap=other.__is_livemap,
243
+ crs_initialized=other.__crs_initialized,
244
+ crs=other.__crs,
245
+ )
246
+ dup.props().update(other.props())
247
+ return dup
248
+
249
+ def __init__(self, data, mapping, scales, layers, metainfo_list=[], is_livemap=False, crs_initialized=False,
250
+ crs=None, **kwargs):
251
+ """Initialize self."""
252
+ super().__init__('plot', name=None, data=data, mapping=mapping, **kwargs)
253
+ self.__scales = list(scales)
254
+ self.__layers = list(layers)
255
+ self.__metainfo_list = list(metainfo_list)
256
+ self.__is_livemap = is_livemap
257
+ self.__crs_initialized = crs_initialized
258
+ self.__crs = crs
259
+
260
+ def get_plot_shared_data(self):
261
+ """
262
+ Extract the data shared by all layers.
263
+
264
+ Returns
265
+ -------
266
+ dict or `DataFrame`
267
+ Object data.
268
+
269
+ Examples
270
+ --------
271
+ .. jupyter-execute::
272
+ :linenos:
273
+ :emphasize-lines: 5
274
+
275
+ from lets_plot import *
276
+ LetsPlot.setup_html()
277
+ p = ggplot({'x': [0], 'y': [0]}, aes('x', 'y'))
278
+ p += geom_point(data={'x': [1], 'y': [1]})
279
+ p.get_plot_shared_data()
280
+
281
+ """
282
+ # used to evaluate 'completion'
283
+ return self.props()['data']
284
+
285
+ def has_layers(self) -> bool:
286
+ """
287
+ Check if the `PlotSpec` object has at least one layer.
288
+
289
+ Returns
290
+ -------
291
+ bool
292
+ True if object has layers.
293
+
294
+ Examples
295
+ --------
296
+ .. jupyter-execute::
297
+ :linenos:
298
+ :emphasize-lines: 4, 6
299
+
300
+ from lets_plot import *
301
+ LetsPlot.setup_html()
302
+ p = ggplot()
303
+ print(p.has_layers())
304
+ p += geom_point(x=0, y=0)
305
+ print(p.has_layers())
306
+
307
+ """
308
+ return True if self.__layers else False
309
+
310
+ def __add__(self, other):
311
+ """
312
+ Allow to add different specs to the `PlotSpec` object.
313
+
314
+ Examples
315
+ --------
316
+ .. jupyter-execute::
317
+ :linenos:
318
+ :emphasize-lines: 7
319
+
320
+ from lets_plot import *
321
+ LetsPlot.setup_html()
322
+ p = ggplot({'x': [0, 1, 2], 'y': [0, 1, 2]}, aes('x', 'y'))
323
+ l = layer('point', mapping=aes(color='x'))
324
+ s = scale_color_discrete()
325
+ t = theme(axis_title='blank')
326
+ p + l + s + t
327
+
328
+ """
329
+ """
330
+ plot + other_plot -> fail
331
+ plot + layer -> plot[layers] += layer
332
+ plot + geom -> plot[layers] += new layer(geom)
333
+ plot + scale -> plot[scales] += scale
334
+ plot + metainfo -> plot[metainfo_list] += metainfo
335
+ plot + [feature] -> plot + each feature in []
336
+ plot + theme + theme -> merged theme
337
+ """
338
+ if isinstance(other, PlotSpec):
339
+ # pass and fail
340
+ pass
341
+
342
+ if isinstance(other, DummySpec):
343
+ # nothing
344
+ return self
345
+
346
+ elif isinstance(other, FeatureSpec):
347
+ plot = PlotSpec.duplicate(self)
348
+ if other.kind == 'layer':
349
+ if other.props()['geom'] == 'livemap':
350
+ plot.__is_livemap = True
351
+
352
+ from lets_plot.plot.util import is_geo_data_frame # local import to break circular reference
353
+ if is_geo_data_frame(other.props().get('data')) \
354
+ or is_geo_data_frame(other.props().get('map')):
355
+ if plot.__crs_initialized:
356
+ if plot.__crs != other.props().get('use_crs'):
357
+ raise ValueError(
358
+ 'All geoms with map parameter should either use same `use_crs` or not use it at all')
359
+ else:
360
+ plot.__crs_initialized = True
361
+ plot.__crs = other.props().get('use_crs')
362
+
363
+ if plot.__is_livemap and plot.__crs is not None:
364
+ raise ValueError("livemap doesn't support `use_crs`")
365
+
366
+ other.before_append(plot.__is_livemap)
367
+ plot.__layers.append(other)
368
+ return plot
369
+
370
+ if other.kind == 'scale':
371
+ plot.__scales.append(other)
372
+ return plot
373
+
374
+ if other.kind == 'theme':
375
+ new_theme_options = {k: v for k, v in other.props().items() if v is not None}
376
+ if 'name' in new_theme_options:
377
+ # keep the previously specified flavor
378
+ if plot.props().get('theme', {}).get('flavor', None) is not None:
379
+ new_theme_options.update({'flavor': plot.props()['theme']['flavor']})
380
+
381
+ # pre-configured theme overrides existing theme altogether.
382
+ plot.props()['theme'] = new_theme_options
383
+ else:
384
+ # merge themes
385
+ old_theme_options = plot.props().get('theme', {})
386
+ plot.props()['theme'] = _theme_dicts_merge(old_theme_options, new_theme_options)
387
+
388
+ return plot
389
+
390
+ if other.kind == 'metainfo':
391
+ plot.__metainfo_list.append(other)
392
+ return plot
393
+
394
+ if isinstance(other, FeatureSpecArray):
395
+ for spec in other.elements():
396
+ plot = plot.__add__(spec)
397
+ return plot
398
+
399
+ if other.kind == 'guides':
400
+ existing_options = plot.props().get('guides', {})
401
+ plot.props()['guides'] = _merge_dicts_recursively(existing_options, other.as_dict())
402
+ return plot
403
+
404
+ if other.kind == 'mapping': # +aes(..)
405
+ existing_spec = plot.props().get('mapping', aes())
406
+ merged_mapping = {**existing_spec.as_dict(), **other.as_dict()}
407
+ plot.props()['mapping'] = aes(**merged_mapping)
408
+ return plot
409
+
410
+ # add feature to properties
411
+ plot.props()[other.kind] = other
412
+ return plot
413
+
414
+ return super().__add__(other)
415
+
416
+ def as_dict(self):
417
+ d = super().as_dict()
418
+ d['kind'] = self.kind
419
+ d['scales'] = [scale.as_dict() for scale in self.__scales]
420
+ d['layers'] = [layer.as_dict() for layer in self.__layers]
421
+ d['metainfo_list'] = [metainfo.as_dict() for metainfo in self.__metainfo_list]
422
+ return d
423
+
424
+ def __str__(self):
425
+ result = ['plot']
426
+ result.extend('{}: {}'.format(k, v)
427
+ for k, v in self.props().items())
428
+
429
+ result.append('scales [{}]'.format(len(self.__scales)))
430
+ for scale in self.__scales:
431
+ result.append(str(scale))
432
+ result.append('-' * 34)
433
+
434
+ result.append('layers [{}]'.format(len(self.__layers)))
435
+ for layer in self.__layers:
436
+ result.append(str(layer))
437
+ result.append('-' * 34)
438
+
439
+ result.append('metainfo_list [{}]'.format(len(self.__metainfo_list)))
440
+ for metainfo in self.__metainfo_list:
441
+ result.append(str(metainfo))
442
+ result.append('-' * 34)
443
+
444
+ result.append('') # for trailing \n
445
+ return '\n'.join(result)
446
+
447
+ def _repr_html_(self):
448
+ # Special method discovered and invoked by IPython.display.display.
449
+ from ..frontend_context._configuration import _as_html
450
+ return _as_html(self.as_dict())
451
+
452
+ def show(self):
453
+ """
454
+ Draw a plot.
455
+
456
+ Examples
457
+ --------
458
+ .. jupyter-execute::
459
+ :linenos:
460
+ :emphasize-lines: 4
461
+
462
+ from lets_plot import *
463
+ LetsPlot.setup_html()
464
+ p = ggplot() + geom_point(x=0, y=0)
465
+ p.show()
466
+
467
+ """
468
+ from ..frontend_context._configuration import _display_plot
469
+ _display_plot(self)
470
+
471
+ def to_svg(self, path=None) -> str:
472
+ """
473
+ Export the plot in SVG format.
474
+
475
+ Parameters
476
+ ----------
477
+ self : `PlotSpec`
478
+ Plot specification to export.
479
+ path : str, file-like object, default=None
480
+ Сan be either a string specifying a file path or a file-like object.
481
+ If a string is provided, the result will be exported to the file at that path.
482
+ If a file-like object is provided, the result will be exported to that object.
483
+ If None is provided, the result will be returned as a string.
484
+
485
+ Returns
486
+ -------
487
+ str
488
+ Absolute pathname of created file,
489
+ SVG content as a string or None if a file-like object is provided.
490
+
491
+ Examples
492
+ --------
493
+ .. jupyter-execute::
494
+ :linenos:
495
+ :emphasize-lines: 9
496
+
497
+ import numpy as np
498
+ import io
499
+ from lets_plot import *
500
+ from IPython import display
501
+ LetsPlot.setup_html()
502
+ x = np.random.randint(10, size=100)
503
+ p = ggplot({'x': x}, aes(x='x')) + geom_bar()
504
+ file_like = io.BytesIO()
505
+ p.to_svg(file_like)
506
+ display.SVG(file_like.getvalue())
507
+ """
508
+ return _to_svg(self, path)
509
+
510
+ def to_html(self, path=None, iframe: bool = None) -> str:
511
+ """
512
+ Export the plot in HTML format.
513
+
514
+ Parameters
515
+ ----------
516
+ self : `PlotSpec`
517
+ Plot specification to export.
518
+ path : str, file-like object, default=None
519
+ Сan be either a string specifying a file path or a file-like object.
520
+ If a string is provided, the result will be exported to the file at that path.
521
+ If a file-like object is provided, the result will be exported to that object.
522
+ If None is provided, the result will be returned as a string.
523
+ iframe : bool, default=False
524
+ Whether to wrap HTML page into a iFrame.
525
+
526
+ Returns
527
+ -------
528
+ str
529
+ Absolute pathname of created file,
530
+ HTML content as a string or None if a file-like object is provided.
531
+
532
+ Examples
533
+ --------
534
+ .. jupyter-execute::
535
+ :linenos:
536
+ :emphasize-lines: 8
537
+
538
+ import numpy as np
539
+ import io
540
+ from lets_plot import *
541
+ LetsPlot.setup_html()
542
+ x = np.random.randint(10, size=100)
543
+ p = ggplot({'x': x}, aes(x='x')) + geom_bar()
544
+ file_like = io.BytesIO()
545
+ p.to_html(file_like)
546
+ """
547
+ return _to_html(self, path, iframe)
548
+
549
+ def to_png(self, path, scale: float = None, w=None, h=None, unit=None, dpi=None) -> str:
550
+ """
551
+ Export a plot to a file or to a file-like object in PNG format.
552
+
553
+ Parameters
554
+ ----------
555
+ self : `PlotSpec`
556
+ Plot specification to export.
557
+ path : str, file-like object
558
+ Сan be either a string specifying a file path or a file-like object.
559
+ If a string is provided, the result will be exported to the file at that path.
560
+ If a file-like object is provided, the result will be exported to that object.
561
+ scale : float
562
+ Scaling factor for raster output. Default value is 2.0.
563
+ w : float, default=None
564
+ Width of the output image in units.
565
+ Only applicable when exporting to PNG or PDF.
566
+ h : float, default=None
567
+ Height of the output image in units.
568
+ Only applicable when exporting to PNG or PDF.
569
+ unit : {'in', 'cm', 'mm'}, default=None
570
+ Unit of the output image. One of: 'in', 'cm', 'mm'.
571
+ Only applicable when exporting to PNG or PDF.
572
+ dpi : int, default=None
573
+ Resolution in dots per inch.
574
+ Only applicable when exporting to PNG or PDF.
575
+
576
+ Returns
577
+ -------
578
+ str
579
+ Absolute pathname of created file or None if a file-like object is provided.
580
+
581
+ Notes
582
+ -----
583
+ Export to PNG file uses the CairoSVG library.
584
+ CairoSVG is free and distributed under the LGPL-3.0 license.
585
+ For more details visit: https://cairosvg.org/documentation/
586
+
587
+ Examples
588
+ --------
589
+ .. jupyter-execute::
590
+ :linenos:
591
+ :emphasize-lines: 9
592
+
593
+ import numpy as np
594
+ import io
595
+ from lets_plot import *
596
+ from IPython import display
597
+ LetsPlot.setup_html()
598
+ x = np.random.randint(10, size=100)
599
+ p = ggplot({'x': x}, aes(x='x')) + geom_bar()
600
+ file_like = io.BytesIO()
601
+ p.to_png(file_like)
602
+ display.Image(file_like.getvalue())
603
+ """
604
+ return _export_as_raster(self, path, scale, 'png', w=w, h=h, unit=unit, dpi=dpi)
605
+
606
+ def to_pdf(self, path, scale: float = None, w=None, h=None, unit=None, dpi=None) -> str:
607
+ """
608
+ Export a plot to a file or to a file-like object in PDF format.
609
+
610
+ Parameters
611
+ ----------
612
+ self : `PlotSpec`
613
+ Plot specification to export.
614
+ path : str, file-like object
615
+ Сan be either a string specifying a file path or a file-like object.
616
+ If a string is provided, the result will be exported to the file at that path.
617
+ If a file-like object is provided, the result will be exported to that object.
618
+ scale : float
619
+ Scaling factor for raster output. Default value is 2.0.
620
+ w : float, default=None
621
+ Width of the output image in units.
622
+ Only applicable when exporting to PNG or PDF.
623
+ h : float, default=None
624
+ Height of the output image in units.
625
+ Only applicable when exporting to PNG or PDF.
626
+ unit : {'in', 'cm', 'mm'}, default=None
627
+ Unit of the output image. One of: 'in', 'cm', 'mm'.
628
+ Only applicable when exporting to PNG or PDF.
629
+ dpi : int, default=None
630
+ Resolution in dots per inch.
631
+ Only applicable when exporting to PNG or PDF.
632
+
633
+ Returns
634
+ -------
635
+ str
636
+ Absolute pathname of created file or None if a file-like object is provided.
637
+
638
+ Notes
639
+ -----
640
+ Export to PDF file uses the CairoSVG library.
641
+ CairoSVG is free and distributed under the LGPL-3.0 license.
642
+ For more details visit: https://cairosvg.org/documentation/
643
+
644
+ Examples
645
+ --------
646
+ .. jupyter-execute::
647
+ :linenos:
648
+ :emphasize-lines: 13
649
+
650
+ import numpy as np
651
+ import io
652
+ import os
653
+ from lets_plot import *
654
+ from IPython import display
655
+ LetsPlot.setup_html()
656
+ n = 60
657
+ np.random.seed(42)
658
+ x = np.random.choice(list('abcde'), size=n)
659
+ y = np.random.normal(size=n)
660
+ p = ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + geom_jitter()
661
+ file_like = io.BytesIO()
662
+ p.to_pdf(file_like)
663
+ """
664
+ return _export_as_raster(self, path, scale, 'pdf', w=w, h=h, unit=unit, dpi=dpi)
665
+
666
+
667
+ class LayerSpec(FeatureSpec):
668
+ """
669
+ A class of the plot layer object.
670
+
671
+ Do not use this class explicitly.
672
+
673
+ Instead, you should construct its objects with functions `geom_point()`,
674
+ `geom_contour()`, `geom_boxplot()`, `geom_text()` etc.
675
+ """
676
+
677
+ __own_features = ['geom', 'stat', 'mapping', 'position']
678
+
679
+ @classmethod
680
+ def duplicate(cls, other):
681
+ # A shallow copy!
682
+ return LayerSpec(**other.props())
683
+
684
+ def __init__(self, **kwargs):
685
+ super().__init__('layer', name=None, **kwargs)
686
+
687
+ def before_append(self, is_livemap):
688
+ from .util import normalize_map_join, is_geo_data_frame, auto_join_geo_names, geo_data_frame_to_crs, \
689
+ get_geo_data_frame_meta
690
+ from lets_plot.geo_data_internals.utils import is_geocoder
691
+
692
+ name = self.props()['geom']
693
+ map_join = self.props().get('map_join')
694
+ map = self.props().get('map')
695
+ map_data_meta = None
696
+
697
+ if map_join is None and map is None:
698
+ return
699
+
700
+ map_join = normalize_map_join(map_join)
701
+
702
+ if is_geocoder(map):
703
+ if is_livemap and get_global_bool(FRAGMENTS_ENABLED) if has_global_value(FRAGMENTS_ENABLED) else False:
704
+ map = map.get_geocodes()
705
+ map_join = auto_join_geo_names(map_join, map)
706
+ map_data_meta = {'georeference': {}}
707
+ else:
708
+ # Fetch proper GeoDataFrame. Further processing is the same as if map was a GDF.
709
+ if name in ['point', 'pie', 'text', 'label', 'livemap']:
710
+ map = map.get_centroids()
711
+ elif name in ['map', 'polygon']:
712
+ map = map.get_boundaries()
713
+ elif name in ['rect']:
714
+ map = map.get_limits()
715
+ else:
716
+ raise ValueError("Geocoding doesn't provide geometries for geom_{}".format(name))
717
+
718
+ if is_geo_data_frame(map):
719
+ # map = geo_data_frame_to_crs(map, self.props().get('use_crs'))
720
+ use_crs = self.props().get('use_crs')
721
+ if use_crs != "provided":
722
+ map = geo_data_frame_to_crs(map, use_crs)
723
+ map_join = auto_join_geo_names(map_join, map)
724
+ map_data_meta = get_geo_data_frame_meta(map)
725
+
726
+ if map_join is not None:
727
+ self.props()['map_join'] = map_join
728
+
729
+ if map is not None:
730
+ self.props()['map'] = map
731
+
732
+ if map_data_meta is not None:
733
+ self.props()['map_data_meta'] = map_data_meta
734
+
735
+ def get_plot_layer_data(self):
736
+ # used to evaluate 'completion'
737
+ return self.props()['data']
738
+
739
+ def __add__(self, other):
740
+ if isinstance(other, DummySpec):
741
+ # nothing
742
+ return self
743
+
744
+ """
745
+ layer + own_feature -> layer[feature] = feature
746
+ layer + other -> default
747
+ """
748
+ if isinstance(other, FeatureSpec):
749
+ if other.kind in LayerSpec.__own_features:
750
+ l = LayerSpec.duplicate(self)
751
+ l.props()[other.kind] = other
752
+ return l
753
+
754
+ return super().__add__(other)
755
+
756
+
757
+ class FeatureSpecArray(FeatureSpec):
758
+ def __init__(self, *features):
759
+ super().__init__('feature-list', name=None)
760
+ self.__elements = []
761
+ self._flatten(list(features), self.__elements)
762
+
763
+ def __len__(self):
764
+ return len(self.__elements)
765
+
766
+ def __iter__(self):
767
+ return self.__elements.__iter__()
768
+
769
+ def __getitem__(self, item):
770
+ return self.__elements[item]
771
+
772
+ def elements(self):
773
+ return self.__elements
774
+
775
+ def as_dict(self):
776
+ elements = [{e.kind: e.as_dict()} for e in self.__elements]
777
+ return {'feature-list': elements}
778
+
779
+ def __add__(self, other):
780
+ if isinstance(other, DummySpec):
781
+ # nothing
782
+ return self
783
+
784
+ """
785
+ array + other_feature -> [my_elements, other]
786
+ array + other_array -> [my_elements, other_elements]
787
+ layer + ? -> fail
788
+ """
789
+ if isinstance(other, FeatureSpec):
790
+ if isinstance(other, FeatureSpecArray):
791
+ return FeatureSpecArray(*self.__elements, *other.__elements)
792
+
793
+ elif other.kind != 'plot':
794
+ return FeatureSpecArray(*self.__elements, other)
795
+
796
+ return super().__add__(other)
797
+
798
+ def _flatten(self, features, out):
799
+ for feature in features:
800
+ if isinstance(feature, FeatureSpecArray):
801
+ self._flatten(feature.elements(), out)
802
+ else:
803
+ out.append(feature)
804
+
805
+
806
+ class DummySpec(FeatureSpec):
807
+ def __init__(self):
808
+ super().__init__('dummy', name=None)
809
+
810
+ def as_dict(self):
811
+ return {'dummy-feature': True}
812
+
813
+ def __add__(self, other):
814
+ return other
815
+
816
+
817
+ def _generate_data(size):
818
+ """ For testing reasons only """
819
+ # return FeatureSpec('dummy', name=None, data='x' * size)
820
+ return PlotSpec(data='x' * size, mapping=None, scales=[], layers=[])
821
+
822
+
823
+ def _merge_dicts_recursively(d1, d2):
824
+ merged = d1.copy()
825
+ for key, value in d2.items():
826
+ if isinstance(value, dict) and isinstance(merged.get(key), dict):
827
+ merged[key] = _merge_dicts_recursively(merged[key], value)
828
+ else:
829
+ merged[key] = value
830
+ return merged
831
+
832
+
833
+ def _theme_dicts_merge(x, y):
834
+ """
835
+ Simple values in `y` override values in `x`.
836
+ If values in `y` and `x` both are dictionaries, then they are merged.
837
+ """
838
+ overlapping_keys = x.keys() & y.keys()
839
+ z = {k: {**x[k], **y[k]} for k in overlapping_keys if type(x[k]) is dict and type(y[k]) is dict}
840
+ return {**x, **y, **z}
841
+
842
+
843
+ def _to_svg(spec, path) -> Union[str, None]:
844
+ from .. import _kbridge as kbr
845
+
846
+ svg = kbr._generate_svg(spec.as_dict())
847
+ if path is None:
848
+ return svg
849
+ elif isinstance(path, str):
850
+ abspath = _makedirs(path)
851
+ with io.open(abspath, mode="w", encoding="utf-8") as f:
852
+ f.write(svg)
853
+ return abspath
854
+ else:
855
+ path.write(svg.encode())
856
+ return None
857
+
858
+
859
+ def _to_html(spec, path, iframe: bool) -> Union[str, None]:
860
+ if iframe is None:
861
+ iframe = False
862
+
863
+ from .. import _kbridge as kbr
864
+ html_page = kbr._generate_static_html_page(spec.as_dict(), iframe)
865
+
866
+ if path is None:
867
+ return html_page
868
+ elif isinstance(path, str):
869
+ abspath = _makedirs(path)
870
+ with io.open(abspath, mode="w", encoding="utf-8") as f:
871
+ f.write(html_page)
872
+ return abspath
873
+ else:
874
+ path.write(html_page.encode())
875
+ return None
876
+
877
+
878
+ def _export_as_raster(spec, path, scale: float, export_format: str, w=None, h=None, unit=None, dpi=None) -> Union[
879
+ str, None]:
880
+ try:
881
+ import cairosvg
882
+ except ImportError:
883
+ import sys
884
+ print("\n"
885
+ "To export Lets-Plot figure to a PNG or PDF file please install CairoSVG library"
886
+ "to your Python environment.\n"
887
+ "CairoSVG is free and distributed under the LGPL-3.0 license.\n"
888
+ "For more details visit: https://cairosvg.org/documentation/\n", file=sys.stderr)
889
+ return None
890
+
891
+ if export_format.lower() == 'png':
892
+ export_function = cairosvg.svg2png
893
+ elif export_format.lower() == 'pdf':
894
+ export_function = cairosvg.svg2pdf
895
+ else:
896
+ raise ValueError("Unknown export format: {}".format(export_format))
897
+
898
+ from .. import _kbridge
899
+ # Use SVG image-rendering style as Cairo doesn't support CSS image-rendering style,
900
+ svg = _kbridge._generate_svg(spec.as_dict(), use_css_pixelated_image_rendering=False)
901
+
902
+ if isinstance(path, str):
903
+ abspath = _makedirs(path)
904
+ result = abspath
905
+ else:
906
+ result = None # file-like object is provided. No path to return.
907
+
908
+ if any(it is not None for it in [w, h, unit, dpi]):
909
+ if w is None or h is None or unit is None or dpi is None:
910
+ raise ValueError("w, h, unit, and dpi must all be specified")
911
+
912
+ w, h = _to_inches(w, unit) * dpi, _to_inches(h, unit) * dpi
913
+ export_function(bytestring=svg, write_to=path, dpi=dpi, output_width=w, output_height=h)
914
+ else:
915
+ scale = scale if scale is not None else 2.0
916
+ export_function(bytestring=svg, write_to=path, scale=scale)
917
+
918
+ return result
919
+
920
+
921
+ def _makedirs(path: str) -> str:
922
+ """Return absolute path to a file after creating all directories in the path."""
923
+ abspath = os.path.abspath(path)
924
+ dirname = os.path.dirname(abspath)
925
+ if dirname and not os.path.exists(dirname):
926
+ os.makedirs(dirname)
927
+ return abspath
928
+
929
+
930
+ def _to_inches(size, size_unit):
931
+ if size_unit is None:
932
+ raise ValueError("Unit must be specified")
933
+
934
+ if size_unit == 'in':
935
+ inches = size
936
+ elif size_unit == 'cm':
937
+ inches = size / 2.54
938
+ elif size_unit == 'mm':
939
+ inches = size / 25.4
940
+ else:
941
+ raise ValueError("Unknown unit: {}. Expected one of: 'in', 'cm', 'mm'".format(size_unit))
942
+
943
+ return inches