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