lets-plot 4.7.0rc1__cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.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 (95) hide show
  1. lets_plot/__init__.py +283 -0
  2. lets_plot/_global_settings.py +196 -0
  3. lets_plot/_kbridge.py +141 -0
  4. lets_plot/_type_utils.py +133 -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 +333 -0
  14. lets_plot/export/__init__.py +6 -0
  15. lets_plot/export/ggsave_.py +141 -0
  16. lets_plot/frontend_context/__init__.py +8 -0
  17. lets_plot/frontend_context/_configuration.py +151 -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 +19 -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 +3 -0
  48. lets_plot/plot/__init__.py +64 -0
  49. lets_plot/plot/_global_theme.py +14 -0
  50. lets_plot/plot/annotation.py +290 -0
  51. lets_plot/plot/coord.py +242 -0
  52. lets_plot/plot/core.py +1060 -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 +8839 -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 +392 -0
  60. lets_plot/plot/geom_livemap_.py +310 -0
  61. lets_plot/plot/ggbunch_.py +96 -0
  62. lets_plot/plot/gggrid_.py +126 -0
  63. lets_plot/plot/ggtb_.py +55 -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 +320 -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 +1342 -0
  76. lets_plot/plot/series_meta.py +203 -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 +772 -0
  81. lets_plot/plot/theme_set.py +393 -0
  82. lets_plot/plot/tooltip.py +486 -0
  83. lets_plot/plot/util.py +237 -0
  84. lets_plot/settings_utils.py +244 -0
  85. lets_plot/tilesets.py +429 -0
  86. lets_plot-4.7.0rc1.dist-info/METADATA +196 -0
  87. lets_plot-4.7.0rc1.dist-info/RECORD +95 -0
  88. lets_plot-4.7.0rc1.dist-info/WHEEL +6 -0
  89. lets_plot-4.7.0rc1.dist-info/licenses/LICENSE +21 -0
  90. lets_plot-4.7.0rc1.dist-info/licenses/licenses/LICENSE.FreeType +166 -0
  91. lets_plot-4.7.0rc1.dist-info/licenses/licenses/LICENSE.ImageMagick +106 -0
  92. lets_plot-4.7.0rc1.dist-info/licenses/licenses/LICENSE.expat +21 -0
  93. lets_plot-4.7.0rc1.dist-info/licenses/licenses/LICENSE.fontconfig +200 -0
  94. lets_plot-4.7.0rc1.dist-info/top_level.txt +2 -0
  95. lets_plot_kotlin_bridge.cpython-311-aarch64-linux-gnu.so +0 -0
lets_plot/plot/core.py ADDED
@@ -0,0 +1,1060 @@
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, MAGICK_EXPORT
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', '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='in'
570
+ Unit of the output image. One of: 'in', 'cm', 'mm'.
571
+ Only applicable when exporting to PNG or PDF.
572
+ dpi : int, default=300
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
+ - If `w`, `h`, `unit`, and `dpi` are all specified:
584
+
585
+ - The plot's pixel size (default or set by `ggsize()`) is ignored.
586
+ - The output size is calculated using the specified `w`, `h`, `unit`, and `dpi`.
587
+
588
+ - The plot is resized to fit the specified `w` x `h` area, which may affect the layout, tick labels, and other elements.
589
+
590
+ - If only `dpi` is specified:
591
+
592
+ - The plot's pixel size (default or set by `ggsize()`) is converted to inches using the standard display PPI of 96.
593
+ - The output size is then calculated based on the specified DPI.
594
+
595
+ - The plot maintains its aspect ratio, preserving layout, tick labels, and other visual elements.
596
+ - Useful for printing - the plot will appear nearly the same size as on screen.
597
+
598
+ - If `w`, `h` are not specified:
599
+
600
+ - The `scale` parameter is used to determine the output size.
601
+
602
+ - The plot maintains its aspect ratio, preserving layout, tick labels, and other visual elements.
603
+ - Useful for generating high-resolution images suitable for publication.
604
+
605
+ Examples
606
+ --------
607
+ .. jupyter-execute::
608
+ :linenos:
609
+ :emphasize-lines: 9
610
+
611
+ import numpy as np
612
+ import io
613
+ from lets_plot import *
614
+ from IPython import display
615
+ LetsPlot.setup_html()
616
+ x = np.random.randint(10, size=100)
617
+ p = ggplot({'x': x}, aes(x='x')) + geom_bar()
618
+ file_like = io.BytesIO()
619
+ p.to_png(file_like)
620
+ display.Image(file_like.getvalue())
621
+
622
+ """
623
+ return _export_as_raster(self, path, scale, 'png', w=w, h=h, unit=unit, dpi=dpi)
624
+
625
+ def to_pdf(self, path, scale: float = None, w=None, h=None, unit=None, dpi=None) -> str:
626
+ """
627
+ Export a plot to a file or to a file-like object in PDF format.
628
+
629
+ Parameters
630
+ ----------
631
+ self : `PlotSpec`
632
+ Plot specification to export.
633
+ path : str, file-like object
634
+ Сan be either a string specifying a file path or a file-like object.
635
+ If a string is provided, the result will be exported to the file at that path.
636
+ If a file-like object is provided, the result will be exported to that object.
637
+ scale : float
638
+ Scaling factor for raster output. Default value is 2.0.
639
+ w : float, default=None
640
+ Width of the output image in units.
641
+ Only applicable when exporting to PNG or PDF.
642
+ h : float, default=None
643
+ Height of the output image in units.
644
+ Only applicable when exporting to PNG or PDF.
645
+ unit : {'in', 'cm', 'mm'}, default='in'
646
+ Unit of the output image. One of: 'in', 'cm', 'mm'.
647
+ Only applicable when exporting to PNG or PDF.
648
+ dpi : int, default=300
649
+ Resolution in dots per inch.
650
+ Only applicable when exporting to PNG or PDF.
651
+
652
+ Returns
653
+ -------
654
+ str
655
+ Absolute pathname of created file or None if a file-like object is provided.
656
+
657
+ Notes
658
+ -----
659
+ - If `w`, `h`, `unit`, and `dpi` are all specified:
660
+
661
+ - The plot's pixel size (default or set by `ggsize()`) is ignored.
662
+ - The output size is calculated using the specified `w`, `h`, `unit`, and `dpi`.
663
+
664
+ - The plot is resized to fit the specified `w` x `h` area, which may affect the layout, tick labels, and other elements.
665
+
666
+ - If only `dpi` is specified:
667
+
668
+ - The plot's pixel size (default or set by `ggsize()`) is converted to inches using the standard display PPI of 96.
669
+ - The output size is then calculated based on the specified DPI.
670
+
671
+ - The plot maintains its aspect ratio, preserving layout, tick labels, and other visual elements.
672
+ - Useful for printing - the plot will appear nearly the same size as on screen.
673
+
674
+ - If `w`, `h` are not specified:
675
+
676
+ - The `scale` parameter is used to determine the output size.
677
+
678
+ - The plot maintains its aspect ratio, preserving layout, tick labels, and other visual elements.
679
+ - Useful for generating high-resolution images suitable for publication.
680
+
681
+ Examples
682
+ --------
683
+ .. jupyter-execute::
684
+ :linenos:
685
+ :emphasize-lines: 13
686
+
687
+ import numpy as np
688
+ import io
689
+ import os
690
+ from lets_plot import *
691
+ from IPython import display
692
+ LetsPlot.setup_html()
693
+ n = 60
694
+ np.random.seed(42)
695
+ x = np.random.choice(list('abcde'), size=n)
696
+ y = np.random.normal(size=n)
697
+ p = ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + geom_jitter()
698
+ file_like = io.BytesIO()
699
+ p.to_pdf(file_like)
700
+
701
+ """
702
+ return _export_as_raster(self, path, scale, 'pdf', w=w, h=h, unit=unit, dpi=dpi)
703
+
704
+
705
+ class LayerSpec(FeatureSpec):
706
+ """
707
+ A class of the plot layer object.
708
+
709
+ Do not use this class explicitly.
710
+
711
+ Instead, you should construct its objects with functions `geom_point()`,
712
+ `geom_contour()`, `geom_boxplot()`, `geom_text()` etc.
713
+ """
714
+
715
+ __own_features = ['geom', 'stat', 'mapping', 'position']
716
+
717
+ @classmethod
718
+ def duplicate(cls, other):
719
+ # A shallow copy!
720
+ return LayerSpec(**other.props())
721
+
722
+ def __init__(self, **kwargs):
723
+ super().__init__('layer', name=None, **kwargs)
724
+
725
+ def before_append(self, is_livemap):
726
+ from .util import normalize_map_join, is_geo_data_frame, auto_join_geo_names, geo_data_frame_to_crs, \
727
+ get_geo_data_frame_meta
728
+ from lets_plot.geo_data_internals.utils import is_geocoder
729
+
730
+ name = self.props()['geom']
731
+ map_join = self.props().get('map_join')
732
+ map = self.props().get('map')
733
+ map_data_meta = None
734
+
735
+ if map_join is None and map is None:
736
+ return
737
+
738
+ map_join = normalize_map_join(map_join)
739
+
740
+ if is_geocoder(map):
741
+ if is_livemap and get_global_bool(FRAGMENTS_ENABLED) if has_global_value(FRAGMENTS_ENABLED) else False:
742
+ map = map.get_geocodes()
743
+ map_join = auto_join_geo_names(map_join, map)
744
+ map_data_meta = {'georeference': {}}
745
+ else:
746
+ # Fetch proper GeoDataFrame. Further processing is the same as if map was a GDF.
747
+ if name in ['point', 'pie', 'text', 'label', 'livemap']:
748
+ map = map.get_centroids()
749
+ elif name in ['map', 'polygon']:
750
+ map = map.get_boundaries()
751
+ elif name in ['rect']:
752
+ map = map.get_limits()
753
+ else:
754
+ raise ValueError("Geocoding doesn't provide geometries for geom_{}".format(name))
755
+
756
+ if is_geo_data_frame(map):
757
+ # map = geo_data_frame_to_crs(map, self.props().get('use_crs'))
758
+ use_crs = self.props().get('use_crs')
759
+ if use_crs != "provided":
760
+ map = geo_data_frame_to_crs(map, use_crs)
761
+ map_join = auto_join_geo_names(map_join, map)
762
+ map_data_meta = get_geo_data_frame_meta(map)
763
+
764
+ if map_join is not None:
765
+ self.props()['map_join'] = map_join
766
+
767
+ if map is not None:
768
+ self.props()['map'] = map
769
+
770
+ if map_data_meta is not None:
771
+ self.props()['map_data_meta'] = map_data_meta
772
+
773
+ def get_plot_layer_data(self):
774
+ # used to evaluate 'completion'
775
+ return self.props()['data']
776
+
777
+ def __add__(self, other):
778
+ if isinstance(other, DummySpec):
779
+ # nothing
780
+ return self
781
+
782
+ """
783
+ layer + own_feature -> layer[feature] = feature
784
+ layer + other -> default
785
+ """
786
+ if isinstance(other, FeatureSpec):
787
+ if other.kind in LayerSpec.__own_features:
788
+ l = LayerSpec.duplicate(self)
789
+ l.props()[other.kind] = other
790
+ return l
791
+
792
+ return super().__add__(other)
793
+
794
+
795
+ class FeatureSpecArray(FeatureSpec):
796
+ def __init__(self, *features):
797
+ super().__init__('feature-list', name=None)
798
+ self.__elements = []
799
+ self._flatten(list(features), self.__elements)
800
+
801
+ def __len__(self):
802
+ return len(self.__elements)
803
+
804
+ def __iter__(self):
805
+ return self.__elements.__iter__()
806
+
807
+ def __getitem__(self, item):
808
+ return self.__elements[item]
809
+
810
+ def elements(self):
811
+ return self.__elements
812
+
813
+ def as_dict(self):
814
+ elements = [{e.kind: e.as_dict()} for e in self.__elements]
815
+ return {'feature-list': elements}
816
+
817
+ def __add__(self, other):
818
+ if isinstance(other, DummySpec):
819
+ # nothing
820
+ return self
821
+
822
+ """
823
+ array + other_feature -> [my_elements, other]
824
+ array + other_array -> [my_elements, other_elements]
825
+ layer + ? -> fail
826
+ """
827
+ if isinstance(other, FeatureSpec):
828
+ if isinstance(other, FeatureSpecArray):
829
+ return FeatureSpecArray(*self.__elements, *other.__elements)
830
+
831
+ elif other.kind != 'plot':
832
+ return FeatureSpecArray(*self.__elements, other)
833
+
834
+ return super().__add__(other)
835
+
836
+ def _flatten(self, features, out):
837
+ for feature in features:
838
+ if isinstance(feature, FeatureSpecArray):
839
+ self._flatten(feature.elements(), out)
840
+ else:
841
+ out.append(feature)
842
+
843
+
844
+ class DummySpec(FeatureSpec):
845
+ def __init__(self):
846
+ super().__init__('dummy', name=None)
847
+
848
+ def as_dict(self):
849
+ return {'dummy-feature': True}
850
+
851
+ def __add__(self, other):
852
+ return other
853
+
854
+
855
+ def _generate_data(size):
856
+ """ For testing reasons only """
857
+ # return FeatureSpec('dummy', name=None, data='x' * size)
858
+ return PlotSpec(data='x' * size, mapping=None, scales=[], layers=[])
859
+
860
+
861
+ def _merge_dicts_recursively(d1, d2):
862
+ merged = d1.copy()
863
+ for key, value in d2.items():
864
+ if isinstance(value, dict) and isinstance(merged.get(key), dict):
865
+ merged[key] = _merge_dicts_recursively(merged[key], value)
866
+ else:
867
+ merged[key] = value
868
+ return merged
869
+
870
+
871
+ def _theme_dicts_merge(x, y):
872
+ """
873
+ Simple values in `y` override values in `x`.
874
+ If values in `y` and `x` both are dictionaries, then they are merged.
875
+ """
876
+ overlapping_keys = x.keys() & y.keys()
877
+ z = {k: {**x[k], **y[k]} for k in overlapping_keys if type(x[k]) is dict and type(y[k]) is dict}
878
+ return {**x, **y, **z}
879
+
880
+
881
+ def _to_svg(spec, path) -> Union[str, None]:
882
+ from .. import _kbridge as kbr
883
+
884
+ svg = kbr._generate_svg(spec.as_dict())
885
+ if path is None:
886
+ return svg
887
+ elif isinstance(path, str):
888
+ abspath = _makedirs(path)
889
+ with io.open(abspath, mode="w", encoding="utf-8") as f:
890
+ f.write(svg)
891
+ return abspath
892
+ else:
893
+ path.write(svg.encode())
894
+ return None
895
+
896
+
897
+ def _to_html(spec, path, iframe: bool) -> Union[str, None]:
898
+ if iframe is None:
899
+ iframe = False
900
+
901
+ from .. import _kbridge as kbr
902
+ html_page = kbr._generate_static_html_page(spec.as_dict(), iframe)
903
+
904
+ if path is None:
905
+ return html_page
906
+ elif isinstance(path, str):
907
+ abspath = _makedirs(path)
908
+ with io.open(abspath, mode="w", encoding="utf-8") as f:
909
+ f.write(html_page)
910
+ return abspath
911
+ else:
912
+ path.write(html_page.encode())
913
+ return None
914
+
915
+
916
+ def _export_as_raster(spec, path, scale: float, export_format: str, w=None, h=None, unit=None, dpi=None) -> Union[str, None]:
917
+ if get_global_bool(MAGICK_EXPORT):
918
+ if w is None and h is None and unit is None and dpi is None:
919
+ def_scale = 2.0
920
+ def_dpi = -1
921
+ def_unit = ""
922
+ else:
923
+ def_scale = 1.0
924
+ def_dpi = 300
925
+ def_unit = 'in'
926
+
927
+ return _export_with_magick(
928
+ spec,
929
+ path,
930
+ scale if scale is not None else def_scale,
931
+ export_format,
932
+ w if w is not None else -1,
933
+ h if h is not None else -1,
934
+ unit if unit is not None else def_unit,
935
+ dpi if dpi is not None else def_dpi
936
+ )
937
+ else:
938
+ return _export_with_cairo(spec, path, scale, export_format, w, h, unit, dpi)
939
+
940
+
941
+ def _export_with_magick(spec, path, scale: float, export_format: str, w, h, unit, dpi) -> Union[str, None]:
942
+ import base64
943
+ from .. import _kbridge
944
+
945
+ if isinstance(path, str):
946
+ file_path = _makedirs(path)
947
+ file_like_object = None
948
+ else:
949
+ file_like_object = path
950
+ file_path = None
951
+
952
+ png_base64 = _kbridge._export_png(spec.as_dict(), float(w), float(h), unit, int(dpi), float(scale))
953
+ png = base64.b64decode(png_base64)
954
+
955
+ if export_format.lower() == 'png':
956
+ if file_path is not None:
957
+ with open(file_path, 'wb') as f:
958
+ f.write(png)
959
+ return file_path
960
+ else:
961
+ file_like_object.write(png)
962
+ return None
963
+ elif export_format.lower() == 'pdf':
964
+ try:
965
+ from PIL import Image
966
+ except ImportError:
967
+ import sys
968
+ print("\n"
969
+ "To export Lets-Plot figure to a PDF file please install pillow library"
970
+ "to your Python environment.\n"
971
+ "Pillow is free and distributed under the MIT-CMU license.\n"
972
+ "For more details visit: https://python-pillow.github.io/\n", file=sys.stderr)
973
+ return None
974
+
975
+
976
+ with Image.open(io.BytesIO(png)) as img:
977
+ if img.mode == 'RGBA':
978
+ img = img.convert('RGB')
979
+
980
+ dpi = dpi if dpi is not None else 96 # Default DPI if not specified
981
+ if file_path is not None:
982
+ img.save(file_path, "PDF", dpi=(dpi, dpi))
983
+ return file_path
984
+ else:
985
+ img.save(file_like_object, "PDF", dpi=(dpi, dpi))
986
+ return None
987
+ else:
988
+ raise ValueError("Unknown export format: {}".format(export_format))
989
+
990
+
991
+ def _export_with_cairo(spec, path, scale: float, export_format: str, w=None, h=None, unit=None, dpi=None) -> Union[str, None]:
992
+ from .. import _kbridge
993
+
994
+ input = None
995
+ export_function = None
996
+
997
+ if export_format.lower() == 'png' or export_format.lower() == 'pdf':
998
+ try:
999
+ import cairosvg
1000
+ except ImportError:
1001
+ import sys
1002
+ print("\n"
1003
+ "To export Lets-Plot figure to a PNG or PDF file please install CairoSVG library"
1004
+ "to your Python environment.\n"
1005
+ "CairoSVG is free and distributed under the LGPL-3.0 license.\n"
1006
+ "For more details visit: https://cairosvg.org/documentation/\n", file=sys.stderr)
1007
+ return None
1008
+
1009
+ if export_format.lower() == 'png':
1010
+ export_function = cairosvg.svg2png
1011
+ elif export_format.lower() == 'pdf':
1012
+ export_function = cairosvg.svg2pdf
1013
+
1014
+ # Use SVG image-rendering style as Cairo doesn't support CSS image-rendering style,
1015
+ input = _kbridge._generate_svg(spec.as_dict(), use_css_pixelated_image_rendering=False)
1016
+ else:
1017
+ raise ValueError("Unknown export format: {}".format(export_format))
1018
+
1019
+ if isinstance(path, str):
1020
+ abspath = _makedirs(path)
1021
+ result = abspath
1022
+ else:
1023
+ result = None # file-like object is provided. No path to return.
1024
+
1025
+ if any(it is not None for it in [w, h, unit, dpi]):
1026
+ if w is None or h is None or unit is None or dpi is None:
1027
+ raise ValueError("w, h, unit, and dpi must all be specified")
1028
+
1029
+ w, h = _to_inches(w, unit) * dpi, _to_inches(h, unit) * dpi
1030
+ export_function(bytestring=input, write_to=path, dpi=dpi, output_width=w, output_height=h)
1031
+ else:
1032
+ scale = scale if scale is not None else 2.0
1033
+ export_function(bytestring=input, write_to=path, scale=scale)
1034
+
1035
+ return result
1036
+
1037
+
1038
+ def _makedirs(path: str) -> str:
1039
+ """Return absolute path to a file after creating all directories in the path."""
1040
+ abspath = os.path.abspath(path)
1041
+ dirname = os.path.dirname(abspath)
1042
+ if dirname and not os.path.exists(dirname):
1043
+ os.makedirs(dirname)
1044
+ return abspath
1045
+
1046
+
1047
+ def _to_inches(size, size_unit):
1048
+ if size_unit is None:
1049
+ raise ValueError("Unit must be specified")
1050
+
1051
+ if size_unit == 'in':
1052
+ inches = size
1053
+ elif size_unit == 'cm':
1054
+ inches = size / 2.54
1055
+ elif size_unit == 'mm':
1056
+ inches = size / 25.4
1057
+ else:
1058
+ raise ValueError("Unknown unit: {}. Expected one of: 'in', 'cm', 'mm'".format(size_unit))
1059
+
1060
+ return inches