-
Notifications
You must be signed in to change notification settings - Fork 49
/
geom.py
6615 lines (5762 loc) · 269 KB
/
geom.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2019. JetBrains s.r.o.
# Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#
from lets_plot.geo_data_internals.utils import is_geocoder
from .core import FeatureSpec, LayerSpec
from .util import as_annotated_data, is_geo_data_frame, geo_data_frame_to_crs, get_geo_data_frame_meta
#
# Geoms, short for geometric objects, describe the type of plot ggplot will produce.
#
__all__ = ['geom_point', 'geom_path', 'geom_line',
'geom_smooth', 'geom_bar',
'geom_histogram', 'geom_dotplot', 'geom_bin2d',
'geom_tile', 'geom_raster',
'geom_errorbar', 'geom_crossbar', 'geom_linerange', 'geom_pointrange',
'geom_contour',
'geom_contourf', 'geom_polygon', 'geom_map',
'geom_abline', 'geom_hline', 'geom_vline',
'geom_boxplot', 'geom_violin', 'geom_ydotplot',
'geom_area_ridges',
'geom_ribbon', 'geom_area', 'geom_density',
'geom_density2d', 'geom_density2df', 'geom_jitter',
'geom_qq', 'geom_qq2', 'geom_qq_line', 'geom_qq2_line',
'geom_freqpoly', 'geom_step', 'geom_rect', 'geom_segment',
'geom_text', 'geom_label', 'geom_pie', 'geom_lollipop',
'geom_count']
def geom_point(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None,
map=None, map_join=None, use_crs=None,
color_by=None, fill_by=None,
**other_args):
"""
Draw points defined by an x and y coordinate, as for a scatter plot.
Parameters
----------
mapping : `FeatureSpec`
Set of aesthetic mappings created by `aes()` function.
Aesthetic mappings describe the way that variables in the data are
mapped to plot "aesthetics".
data : dict or Pandas or Polars `DataFrame` or `GeoDataFrame`
The data to be displayed in this layer. If None, the default, the data
is inherited from the plot data as specified in the call to ggplot.
stat : str, default='identity'
The statistical transformation to use on the data for this layer, as a string.
Supported transformations: 'identity' (leaves the data unchanged),
'count' (counts number of points with same x-axis coordinate),
'bin' (counts number of points with x-axis coordinate in the same bin),
'smooth' (performs smoothing - linear default),
'density' (computes and draws kernel density estimate),
'sum' (counts the number of points at each location - might help to workaround overplotting).
position : str or `FeatureSpec`, default='identity'
Position adjustment, either as a string ('identity', 'stack', 'dodge', ...),
or the result of a call to a position adjustment function.
show_legend : bool, default=True
False - do not show legend for this layer.
sampling : `FeatureSpec`
Result of the call to the `sampling_xxx()` function.
To prevent any sampling for this layer pass value "none" (string "none").
tooltips : `layer_tooltips`
Result of the call to the `layer_tooltips()` function.
Specify appearance, style and content.
map : `GeoDataFrame` or `Geocoder`
Data containing coordinates of points.
map_join : str or list
Keys used to join map coordinates with data.
First value in pair - column/columns in `data`.
Second value in pair - column/columns in `map`.
use_crs : str, optional, default="EPSG:4326" (aka WGS84)
EPSG code of the coordinate reference system (CRS) or the keyword "provided".
If an EPSG code is given, then all the coordinates in `GeoDataFrame` (see the `map` parameter)
will be projected to this CRS.
Specify "provided" to disable any further re-projection and to keep the `GeoDataFrame’s` original CRS.
color_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='color'
Define the color aesthetic for the geometry.
fill_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='fill'
Define the fill aesthetic for the geometry.
other_args
Other arguments passed on to the layer.
These are often aesthetics settings used to set an aesthetic to a fixed value,
like color='red', fill='blue', size=3 or shape=21.
They may also be parameters to the paired geom/stat.
Returns
-------
`LayerSpec`
Geom object specification.
Notes
-----
The point geometry is used to create scatterplots.
The scatterplot is useful for displaying the relationship between
two continuous variables, although it can also be used with one continuous
and one categorical variable, or two categorical variables.
`geom_point()` understands the following aesthetics mappings:
- x : x-axis value.
- y : y-axis value.
- alpha : transparency level of the point. Accept values between 0 and 1.
- color (colour) : color of the geometry. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- fill : fill color. Is applied only to the points of shapes having inner area. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- shape : shape of the point, an integer from 0 to 25.
- size : size of the point.
- stroke : width of the shape border. Applied only to the shapes having border.
|
The `data` and `map` parameters of `GeoDataFrame` type support shapes `Point` and `MultiPoint`.
The `map` parameter of `Geocoder` type implicitly invokes `centroids()` function.
|
The conventions for the values of `map_join` parameter are as follows:
- Joining data and `GeoDataFrame` object
Data has a column named 'State_name' and `GeoDataFrame` has a matching column named 'state':
- map_join=['State_Name', 'state']
- map_join=[['State_Name'], ['state']]
- Joining data and `Geocoder` object
Data has a column named 'State_name'. The matching key in `Geocoder` is always 'state' (providing it is a state-level geocoder) and can be omitted:
- map_join='State_Name'
- map_join=['State_Name']
- Joining data by composite key
Joining by composite key works like in examples above, but instead of using a string for a simple key you need to use an array of strings for a composite key. The names in the composite key must be in the same order as in the US street addresses convention: 'city', 'county', 'state', 'country'. For example, the data has columns 'State_name' and 'County_name'. Joining with a 2-keys county level `Geocoder` object (the `Geocoder` keys 'county' and 'state' are omitted in this case):
- map_join=['County_name', 'State_Name']
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 6
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y = np.sin(x)
ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + geom_point()
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 9-10
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
n = 100
x = np.random.uniform(-1, 1, size=n)
y = 25 * x ** 2 + np.random.normal(size=n)
ggplot({'x': x, 'y': y}) + \\
geom_point(aes(x='x', y='y', fill='y'), \\
shape=21, size=5, color='white')
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 8-11
from lets_plot import *
from lets_plot.geo_data import *
LetsPlot.setup_html()
data = {"city": ["New York", "Los Angeles", "Chicago"], \\
"est_pop_2019": [8_336_817, 3_979_576, 2_693_976]}
centroids = geocode_cities(data["city"]).get_centroids()
ggplot() + geom_livemap() + \\
geom_point(aes(size="est_pop_2019"), color="red", show_legend=False, \\
data=data, map=centroids, map_join="city", \\
tooltips=layer_tooltips().title("@city")
.line("population|@est_pop_2019"))
"""
return _geom('point',
mapping=mapping,
data=data,
stat=stat,
position=position,
show_legend=show_legend,
sampling=sampling,
tooltips=tooltips,
map=map, map_join=map_join, use_crs=use_crs,
color_by=color_by, fill_by=fill_by,
**other_args)
def geom_path(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None,
map=None, map_join=None, use_crs=None,
flat=None, geodesic=None,
color_by=None,
**other_args):
"""
Connect observations in the order, how they appear in the data.
Parameters
----------
mapping : `FeatureSpec`
Set of aesthetic mappings created by `aes()` function.
Aesthetic mappings describe the way that variables in the data are
mapped to plot "aesthetics".
data : dict or Pandas or Polars `DataFrame` or `GeoDataFrame`
The data to be displayed in this layer. If None, the default, the data
is inherited from the plot data as specified in the call to ggplot.
stat : str, default='identity'
The statistical transformation to use on the data for this layer, as a string.
Supported transformations: 'identity' (leaves the data unchanged),
'count' (counts number of points with same x-axis coordinate),
'bin' (counts number of points with x-axis coordinate in the same bin),
'smooth' (performs smoothing - linear default),
'density' (computes and draws kernel density estimate).
position : str or `FeatureSpec`, default='identity'
Position adjustment, either as a string ('identity', 'stack', 'dodge', ...),
or the result of a call to a position adjustment function.
show_legend : bool, default=True
False - do not show legend for this layer.
sampling : `FeatureSpec`
Result of the call to the `sampling_xxx()` function.
To prevent any sampling for this layer pass value "none" (string "none").
tooltips : `layer_tooltips`
Result of the call to the `layer_tooltips()` function.
Specify appearance, style and content.
map : `GeoDataFrame`
Data containing coordinates of lines.
map_join : str or list
Keys used to join map coordinates with data.
First value in pair - column/columns in `data`.
Second value in pair - column/columns in `map`.
use_crs : str, optional, default="EPSG:4326" (aka WGS84)
EPSG code of the coordinate reference system (CRS) or the keyword "provided".
If an EPSG code is given, then all the coordinates in `GeoDataFrame` (see the `map` parameter)
will be projected to this CRS.
Specify "provided" to disable any further re-projection and to keep the `GeoDataFrame’s` original CRS.
flat : bool, default=False.
True - keep a line straight (corresponding to a loxodrome in case of Mercator projection).
False - allow a line to be reprojected, so it can become a curve.
geodesic : bool, default=False
Draw geodesic. Coordinates expected to be in WGS84. Works only with `geom_livemap()`.
color_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='color'
Define the color aesthetic for the geometry.
other_args
Other arguments passed on to the layer.
These are often aesthetics settings used to set an aesthetic to a fixed value,
like color='red', fill='blue', size=3 or shape=21.
They may also be parameters to the paired geom/stat.
Returns
-------
`LayerSpec`
Geom object specification.
Notes
-----
`geom_path()` connects the observations in the order in which they appear in the data.
`geom_path()` lets you explore how two variables are related over time.
`geom_path()` understands the following aesthetics mappings:
- x : x-axis value.
- y : y-axis value.
- alpha : transparency level of a layer. Accept values between 0 and 1.
- color (colour) : color of the geometry. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- linetype : type of the line. Codes and names: 0 = 'blank', 1 = 'solid', 2 = 'dashed', 3 = 'dotted', 4 = 'dotdash', 5 = 'longdash', 6 = 'twodash'.
- size : line width.
|
The `data` and `map` parameters of `GeoDataFrame` type support shapes `LineString` and `MultiLineString`.
|
The conventions for the values of `map_join` parameter are as follows.
- Joining data and `GeoDataFrame` object
Data has a column named 'State_name' and `GeoDataFrame` has a matching column named 'state':
- map_join=['State_Name', 'state']
- map_join=[['State_Name'], ['state']]
- Joining data and `Geocoder` object
Data has a column named 'State_name'. The matching key in `Geocoder` is always 'state' (providing it is a state-level geocoder) and can be omitted:
- map_join='State_Name'
- map_join=['State_Name']
- Joining data by composite key
Joining by composite key works like in examples above, but instead of using a string for a simple key you need to use an array of strings for a composite key. The names in the composite key must be in the same order as in the US street addresses convention: 'city', 'county', 'state', 'country'. For example, the data has columns 'State_name' and 'County_name'. Joining with a 2-keys county level `Geocoder` object (the `Geocoder` keys 'county' and 'state' are omitted in this case):
- map_join=['County_name', 'State_Name']
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 7
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
n = 100
t = np.linspace(0, 2 * np.pi, n)
data = {'x': t * np.sin(t), 'y': t * np.cos(t)}
ggplot(data, aes(x='x', y='y')) + geom_path()
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 11
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
T = 50
np.random.seed(42)
x = np.cumsum(np.random.normal(size=2*T))
y = np.cumsum(np.random.normal(size=2*T))
c = [0] * T + [1] * T
data = {'x': x, 'y': y, 'c': c}
ggplot(data, aes(x='x', y='y', group='c')) + \\
geom_path(aes(color='c'), size=2, alpha=.5) + \\
scale_color_discrete()
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 15
from lets_plot import *
from lets_plot.geo_data import *
LetsPlot.setup_html()
pushkin_1829_journey = {
"city": ["Moscow", "Oryol", "Novocherkassk", "Stavropol", \\
"Georgiyevsk", "Vladikavkaz", "Tiflis", "Kars", "Erzurum"],
"latitude": [55.751244, 52.929697, 47.414101, 45.0428, \\
44.1497667, 43.03667, 41.716667, 40.60199, 39.90861],
"longitude": [37.618423, 36.098689, 40.110401, 41.9734, \\
43.4577689, 44.66778, 44.783333, 43.09495, 41.27694],
}
ggplot(pushkin_1829_journey, aes("longitude", "latitude")) + \\
geom_livemap(const_size_zoomin=0) + \\
geom_point(size=3, color="#fc4e2a", tooltips=layer_tooltips().line("@city")) + \\
geom_path(color="#fc4e2a")
"""
return _geom('path',
mapping=mapping,
data=data,
stat=stat,
position=position,
show_legend=show_legend,
sampling=sampling,
tooltips=tooltips,
map=map, map_join=map_join, use_crs=use_crs,
flat=flat, geodesic=geodesic,
color_by=color_by,
**other_args)
def geom_line(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None,
color_by=None,
**other_args):
"""
Connect points in the order of the variable on the x axis.
In case points need to be connected in the order in which they appear in the data,
use `geom_path()`.
Parameters
----------
mapping : `FeatureSpec`
Set of aesthetic mappings created by `aes()` function.
Aesthetic mappings describe the way that variables in the data are
mapped to plot "aesthetics".
data : dict or Pandas or Polars `DataFrame`
The data to be displayed in this layer. If None, the default, the data
is inherited from the plot data as specified in the call to ggplot.
stat : str, default='identity'
The statistical transformation to use on the data for this layer, as a string.
Supported transformations: 'identity' (leaves the data unchanged),
'count' (counts number of points with same x-axis coordinate),
'bin' (counts number of points with x-axis coordinate in the same bin),
'smooth' (performs smoothing - linear default),
'density' (computes and draws kernel density estimate).
position : str or `FeatureSpec`, default='identity'
Position adjustment, either as a string ('identity', 'stack', 'dodge', ...),
or the result of a call to a position adjustment function.
show_legend : bool, default=True
False - do not show legend for this layer.
sampling : `FeatureSpec`
Result of the call to the `sampling_xxx()` function.
To prevent any sampling for this layer pass value "none" (string "none").
tooltips : `layer_tooltips`
Result of the call to the `layer_tooltips()` function.
Specify appearance, style and content.
color_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='color'
Define the color aesthetic for the geometry.
other_args
Other arguments passed on to the layer.
These are often aesthetics settings used to set an aesthetic to a fixed value,
like color='red', fill='blue', size=3 or shape=21.
They may also be parameters to the paired geom/stat.
Returns
-------
`LayerSpec`
Geom object specification.
Notes
-----
`geom_line()` connects the observations in the order of the variable on the x axis.
`geom_line()` can be used to plot time series.
`geom_line()` understands the following aesthetics mappings:
- x : x-axis value.
- y : y-axis value.
- alpha : transparency level of a layer. Accept values between 0 and 1.
- color (colour) : color of the geometry. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- linetype : type of the line. Codes and names: 0 = 'blank', 1 = 'solid', 2 = 'dashed', 3 = 'dotted', 4 = 'dotdash', 5 = 'longdash', 6 = 'twodash.
- size : line width.
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 6
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
x = np.linspace(-4 * np.pi, 4 * np.pi, 100)
y = np.sin(x)
ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + geom_line()
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 12-13
import numpy as np
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
t = np.arange(100)
x1 = np.cumsum(np.random.normal(size=t.size))
x2 = np.cumsum(np.random.normal(size=t.size))
df = pd.DataFrame({'t': t, 'x1': x1, 'x2': x2})
df = pd.melt(df, id_vars=['t'], value_vars=['x1', 'x2'])
ggplot(df, aes(x='t', y='value', group='variable')) + \\
geom_line(aes(color='variable'), size=1, alpha=0.5) + \\
geom_line(stat='smooth', color='red', linetype='longdash')
"""
return _geom('line',
mapping=mapping,
data=data,
stat=stat,
position=position,
show_legend=show_legend,
sampling=sampling,
tooltips=tooltips,
color_by=color_by,
**other_args)
def geom_smooth(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None,
orientation=None,
method=None,
n=None,
se=None,
level=None,
span=None,
deg=None,
seed=None,
max_n=None,
color_by=None, fill_by=None,
**other_args):
"""
Add a smoothed conditional mean.
Parameters
----------
mapping : `FeatureSpec`
Set of aesthetic mappings created by `aes()` function.
Aesthetic mappings describe the way that variables in the data are
mapped to plot "aesthetics".
data : dict or Pandas or Polars `DataFrame`
The data to be displayed in this layer. If None, the default, the data
is inherited from the plot data as specified in the call to ggplot.
stat : str, default='smooth'
The statistical transformation to use on the data for this layer, as a string.
Supported transformations: 'identity' (leaves the data unchanged),
'count' (counts number of points with same x-axis coordinate),
'bin' (counts number of points with x-axis coordinate in the same bin),
'smooth' (performs smoothing - linear default),
'density' (computes and draws kernel density estimate).
position : str or `FeatureSpec`, default='identity'
Position adjustment, either as a string ('identity', 'stack', 'dodge', ...),
or the result of a call to a position adjustment function.
show_legend : bool, default=True
False - do not show legend for this layer.
sampling : `FeatureSpec`
Result of the call to the `sampling_xxx()` function.
To prevent any sampling for this layer pass value "none" (string "none").
tooltips : `layer_tooltips`
Result of the call to the `layer_tooltips()` function.
Specify appearance, style and content.
orientation : str, default='x'
Specify the axis that the layer's stat and geom should run along.
Possible values: 'x', 'y'.
method : str, default='lm'
Smoothing method: 'lm' (Linear Model) or 'loess' (Locally Estimated Scatterplot Smoothing).
If value of `deg` parameter is greater than 1 then linear model becomes polynomial of the given degree.
n : int
Number of points to evaluate smoother at.
se : bool, default=True
Display confidence interval around smooth.
level : float, default=0.95
Level of confidence interval to use.
span : float, default=0.5
Only for 'loess' method. The fraction of source points closest
to the current point is taken into account for computing a least-squares regression.
A sensible value is usually 0.25 to 0.5.
deg : int, default=1
Degree of polynomial for linear regression model.
seed : int
Random seed for 'loess' sampling.
max_n : int, default=1000
Maximum number of data-points for 'loess' method.
If this quantity exceeded random sampling is applied to data.
color_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='color'
Define the color aesthetic for the geometry.
fill_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='fill'
Define the fill aesthetic for the geometry.
other_args
Other arguments passed on to the layer.
These are often aesthetics settings used to set an aesthetic to a fixed value,
like color='red', fill='blue', size=3 or shape=21.
They may also be parameters to the paired geom/stat.
Returns
-------
`LayerSpec`
Geom object specification.
Notes
-----
`geom_smooth()` aids the eye in seeing patterns in the presence of overplotting.
Computed variables:
- ..y.. : predicted (smoothed) value.
- ..ymin.. : lower pointwise confidence interval around the mean.
- ..ymax.. : upper pointwise confidence interval around the mean.
- ..se.. : standard error.
`geom_smooth()` understands the following aesthetics mappings:
- x : x-axis value.
- y : y-axis value.
- alpha : transparency level of a layer. Accept values between 0 and 1.
- color (colour) : color of the geometry. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- fill : fill color for the confidence interval around the line. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- linetype : type of the line of conditional mean line. Codes and names: 0 = 'blank', 1 = 'solid', 2 = 'dashed', 3 = 'dotted', 4 = 'dotdash', 5 = 'longdash', 6 = 'twodash.
- size : line width. Define line width for conditional mean and confidence bounds lines.
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 9
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
n = 50
x = np.arange(n)
y = x + np.random.normal(scale=10, size=n)
ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + \\
geom_point() + geom_smooth()
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 9
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
n = 100
x = np.linspace(-2, 2, n)
y = x ** 2 + np.random.normal(size=n)
ggplot({'x': x, 'y': y}, aes(x='x', y='y')) + \\
geom_point() + geom_smooth(color='red', deg=2, se=False)
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 14-15
import numpy as np
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
t = np.linspace(0, 1, 100)
mean = 1 + np.zeros(2)
cov = np.eye(2)
x, y = np.random.multivariate_normal(mean, cov, t.size).T
df = pd.DataFrame({'t': t, 'x': x, 'y': y})
df = df.melt(id_vars=['t'], value_vars=['x', 'y'])
ggplot(df, aes(x='t', y='value', group='variable')) + \\
geom_point(aes(color='variable'), size=3, alpha=.5) + \\
geom_smooth(aes(color='variable'), size=1, \\
method='loess', span=.3, level=.7, seed=42)
"""
return _geom('smooth',
mapping=mapping,
data=data,
stat=stat,
position=position,
show_legend=show_legend,
sampling=sampling,
tooltips=tooltips,
orientation=orientation,
method=method,
n=n,
se=se,
level=level,
span=span,
deg=deg,
seed=seed,
max_n=max_n,
color_by=color_by, fill_by=fill_by,
**other_args)
def geom_bar(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None,
tooltips=None, labels=None,
orientation=None,
color_by=None, fill_by=None,
**other_args):
"""
Display a bar chart which makes the height of the bar proportional to the
number of observed variable values, mapped to x axis.
Parameters
----------
mapping : `FeatureSpec`
Set of aesthetic mappings created by `aes()` function.
Aesthetic mappings describe the way that variables in the data are
mapped to plot "aesthetics".
data : dict or Pandas or Polars `DataFrame`
The data to be displayed in this layer. If None, the default, the data
is inherited from the plot data as specified in the call to ggplot.
stat : str, default='count'
The statistical transformation to use on the data for this layer, as a string.
Supported transformations: 'identity' (leaves the data unchanged),
'count' (counts number of points with same x-axis coordinate),
'bin' (counts number of points with x-axis coordinate in the same bin),
'smooth' (performs smoothing - linear default),
'density' (computes and draws kernel density estimate).
position : str or `FeatureSpec`, default='stack'
Position adjustment, either as a string ('identity', 'stack', 'dodge', ...),
or the result of a call to a position adjustment function.
show_legend : bool, default=True
False - do not show legend for this layer.
sampling : `FeatureSpec`
Result of the call to the `sampling_xxx()` function.
To prevent any sampling for this layer pass value "none" (string "none").
tooltips : `layer_tooltips`
Result of the call to the `layer_tooltips()` function.
Specify appearance, style and content.
labels : `layer_labels`
Result of the call to the `layer_labels()` function.
Specify style and content of the annotations.
orientation : str, default='x'
Specify the axis that the layer's stat and geom should run along.
Possible values: 'x', 'y'.
color_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='color'
Define the color aesthetic for the geometry.
fill_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='fill'
Define the fill aesthetic for the geometry.
other_args
Other arguments passed on to the layer.
These are often aesthetics settings used to set an aesthetic to a fixed value,
like color='red', fill='blue', size=3 or shape=21.
They may also be parameters to the paired geom/stat.
Returns
-------
`LayerSpec`
Geom object specification.
Notes
-----
`geom_bar()` makes the height of the bar proportional to the number
of observed variable values, mapped to x axis. Is intended to use for discrete data.
If used for continuous data with stat='bin' produces histogram for binned data.
`geom_bar()` handles no group aesthetics.
Computed variables:
- ..count.. : number of points with same x-axis coordinate.
- ..sum.. : total number of points with same x-axis coordinate.
- ..prop.. : groupwise proportion.
- ..proppct.. : groupwise proportion in percent.
`geom_bar()` understands the following aesthetics mappings:
- x : x-axis value (this value will produce cases or bins for bars).
- y : y-axis value (this value will be used to multiply the case's or bin's counts).
- alpha : transparency level of a layer. Accept values between 0 and 1.
- color (colour) : color of the geometry lines. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- fill : fill color. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- size : line width. Define bar line width.
- weight : used by 'count' stat to compute weighted sum instead of simple count.
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 6
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
data = {'x': np.random.randint(10, size=100)}
ggplot(data, aes(x='x')) + geom_bar()
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 9-10
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
n = 10
x = np.arange(n)
y = 1 + np.random.randint(5, size=n)
ggplot() + \\
geom_bar(aes(x='x', y='y', fill='x'), data={'x': x, 'y': y}, \\
stat='identity', show_legend=False) + \\
scale_fill_discrete()
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 9-12
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
n = 5000
x = np.random.normal(size=n)
c = np.random.choice(list('abcde'), size=n)
ggplot({'x': x, 'class': c}, aes(x='x')) + \\
geom_bar(aes(group='class', fill='class', color='class'), \\
stat='bin', sampling=sampling_pick(n=500), alpha=.3, \\
tooltips=layer_tooltips().line('@|@class')
.line('count|@..count..'))
"""
return _geom('bar',
mapping=mapping,
data=data,
stat=stat,
position=position,
show_legend=show_legend,
sampling=sampling,
tooltips=tooltips,
labels=labels,
orientation=orientation,
color_by=color_by, fill_by=fill_by,
**other_args)
def geom_histogram(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None,
tooltips=None, labels=None,
orientation=None,
bins=None,
binwidth=None,
center=None,
boundary=None,
color_by=None, fill_by=None,
**other_args):
"""
Display a 1d distribution by dividing variable mapped to x axis into bins
and counting the number of observations in each bin.
Parameters
----------
mapping : `FeatureSpec`
Set of aesthetic mappings created by `aes()` function.
Aesthetic mappings describe the way that variables in the data are
mapped to plot "aesthetics".
data : dict or Pandas or Polars `DataFrame`
The data to be displayed in this layer. If None, the default, the data
is inherited from the plot data as specified in the call to ggplot.
stat : str, default='bin'
The statistical transformation to use on the data for this layer, as a string.
Supported transformations: 'identity' (leaves the data unchanged),
'count' (counts number of points with same x-axis coordinate),
'bin' (counts number of points with x-axis coordinate in the same bin),
'smooth' (performs smoothing - linear default),
'density' (computes and draws kernel density estimate).
position : str or `FeatureSpec`, default='stack'
Position adjustment, either as a string ('identity', 'stack', 'dodge', ...),
or the result of a call to a position adjustment function.
show_legend : bool, default=True
False - do not show legend for this layer.
sampling : `FeatureSpec`
Result of the call to the `sampling_xxx()` function.
To prevent any sampling for this layer pass value "none" (string "none").
tooltips : `layer_tooltips`
Result of the call to the `layer_tooltips()` function.
Specify appearance, style and content.
labels : `layer_labels`
Result of the call to the `layer_labels()` function.
Specify style and content of the annotations.
orientation : str, default='x'
Specify the axis that the layer's stat and geom should run along.
Possible values: 'x', 'y'.
bins : int, default=30
Number of bins. Overridden by `binwidth`.
binwidth : float
The width of the bins. The default is to use bin widths that cover
the range of the data. You should always override this value,
exploring multiple widths to find the best to illustrate the stories in your data.
center : float
Specify x-value to align bin centers to.
boundary : float
Specify x-value to align bin boundary (i.e. point between bins) to.
color_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='color'
Define the color aesthetic for the geometry.
fill_by : {'fill', 'color', 'paint_a', 'paint_b', 'paint_c'}, default='fill'
Define the fill aesthetic for the geometry.
other_args
Other arguments passed on to the layer.
These are often aesthetics settings used to set an aesthetic to a fixed value,
like color='red', fill='blue', size=3 or shape=21.
They may also be parameters to the paired geom/stat.
Returns
-------
`LayerSpec`
Geom object specification.
Notes
-----
`geom_histogram()` displays a 1d distribution by dividing variable
mapped to x-axis into bins and counting the number of observations in each bin.
Computed variables:
- ..count.. : number of points with x-axis coordinate in the same bin.
- ..binwidth.. : width of each bin.
`geom_histogram()` understands the following aesthetics mappings:
- x : x-axis value (this value will produce cases or bins for bars).
- y : y-axis value, default: '..count..'. Alternatively: '..density..'.
- alpha : transparency level of a layer. Accept values between 0 and 1.
- color (colour) : color of the geometry lines. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- fill : fill color. String in the following formats: RGB/RGBA (e.g. "rgb(0, 0, 255)"); HEX (e.g. "#0000FF"); color name (e.g. "red"); role name ("pen", "paper" or "brush").
- size : line width.
- weight : used by 'bin' stat to compute weighted sum instead of simple count.
Examples
--------
.. jupyter-execute::
:linenos:
:emphasize-lines: 6
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
data = {'x': np.random.normal(size=1000)}
ggplot(data, aes(x='x')) + geom_histogram()
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 7
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
data = {'x': np.random.gamma(2.0, size=1000)}
ggplot(data, aes(x='x')) + \\
geom_histogram(aes(color='x', fill='x'), bins=50)
|
.. jupyter-execute::
:linenos:
:emphasize-lines: 8-10
import numpy as np
from lets_plot import *
LetsPlot.setup_html()
np.random.seed(42)
x = np.random.normal(scale=3, size=1000)
y = 2 * (np.round(x) % 2) - 1
ggplot({'x': x, 'y': y}) + \\
geom_histogram(aes(x='x', weight='y'), \\
center=0, binwidth=1, \\
color='black', fill='gray', size=1)
"""
return _geom('histogram',
mapping=mapping,
data=data,
stat=stat,
position=position,
show_legend=show_legend,
sampling=sampling,
tooltips=tooltips,
labels=labels,
orientation=orientation,
bins=bins,
binwidth=binwidth,
center=center,
boundary=boundary,
color_by=color_by, fill_by=fill_by,
**other_args)
def geom_dotplot(mapping=None, *, data=None, show_legend=None, sampling=None, tooltips=None,
binwidth=None,
bins=None,
method=None,
stackdir=None,
stackratio=None,
dotsize=None,
stackgroups=None,
center=None,
boundary=None,
color_by=None, fill_by=None,
**other_args):
"""
Dotplot represents individual observations in a batch of data with circular dots.
The diameter of a dot corresponds to the maximum width or bin width, depending on the binning algorithm.
Parameters
----------
mapping : `FeatureSpec`
Set of aesthetic mappings created by `aes()` function.
Aesthetic mappings describe the way that variables in the data are
mapped to plot "aesthetics".
data : dict or Pandas or Polars `DataFrame`
The data to be displayed in this layer. If None, the default, the data
is inherited from the plot data as specified in the call to ggplot.
show_legend : bool, default=True
False - do not show legend for this layer.
sampling : `FeatureSpec`
Result of the call to the `sampling_xxx()` function.
To prevent any sampling for this layer pass value "none" (string "none").
tooltips : `layer_tooltips`
Result of the call to the `layer_tooltips()` function.
Specify appearance, style and content.
binwidth : float
When method is 'dotdensity', this specifies maximum bin width.
When method is 'histodot', this specifies bin width.
bins : int, default=30