/
arrow_altair.py
1583 lines (1286 loc) · 56.3 KB
/
arrow_altair.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) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A Python wrapper around Altair.
Altair is a Python visualization library based on Vega-Lite,
a nice JSON schema for expressing graphs and charts.
"""
from __future__ import annotations
from contextlib import nullcontext
from datetime import date
from enum import Enum
from typing import TYPE_CHECKING, Any, Collection, Literal, Sequence, cast
import streamlit.elements.arrow_vega_lite as arrow_vega_lite
from streamlit import type_util
from streamlit.color_util import (
Color,
is_color_like,
is_color_tuple_like,
is_hex_color_like,
to_css_color,
)
from streamlit.elements.altair_utils import AddRowsMetadata
from streamlit.elements.arrow import Data
from streamlit.elements.utils import last_index_for_melted_dataframes
from streamlit.errors import Error, StreamlitAPIException
from streamlit.proto.ArrowVegaLiteChart_pb2 import (
ArrowVegaLiteChart as ArrowVegaLiteChartProto,
)
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
import altair as alt
import pandas as pd
from streamlit.delta_generator import DeltaGenerator
class ChartType(Enum):
AREA = {"mark_type": "area"}
BAR = {"mark_type": "bar"}
LINE = {"mark_type": "line"}
SCATTER = {"mark_type": "circle"}
# Color and size legends need different title paddings in order for them
# to be vertically aligned.
#
# NOTE: I don't think it's possible to *perfectly* align the size and
# color legends in all instances, since the "size" circles vary in size based
# on the data, and their container is top-aligned with the color container. But
# through trial-and-error I found this value to be a good enough middle ground.
# See e2e/scripts/st_arrow_scatter_chart.py for some alignment tests.
#
# NOTE #2: In theory, we could move COLOR_LEGEND_SETTINGS into
# ArrowVegaLiteChart/CustomTheme.tsx, but this would impact existing behavior.
# (See https://github.com/streamlit/streamlit/pull/7164#discussion_r1307707345)
COLOR_LEGEND_SETTINGS = dict(titlePadding=5, offset=5, orient="bottom")
SIZE_LEGEND_SETTINGS = dict(titlePadding=0.5, offset=5, orient="bottom")
# User-readable names to give the index and melted columns.
SEPARATED_INDEX_COLUMN_TITLE = "index"
MELTED_Y_COLUMN_TITLE = "value"
MELTED_COLOR_COLUMN_TITLE = "color"
# Crazy internal (non-user-visible) names for the index and melted columns, in order to
# avoid collision with existing column names. The suffix below was generated with an
# online random number generator. Rationale: because it makes it even less likely to
# lead to a conflict than something that's human-readable (like "--streamlit-fake-field"
# or something).
PROTECTION_SUFFIX = "--p5bJXXpQgvPz6yvQMFiy"
SEPARATED_INDEX_COLUMN_NAME = SEPARATED_INDEX_COLUMN_TITLE + PROTECTION_SUFFIX
MELTED_Y_COLUMN_NAME = MELTED_Y_COLUMN_TITLE + PROTECTION_SUFFIX
MELTED_COLOR_COLUMN_NAME = MELTED_COLOR_COLUMN_TITLE + PROTECTION_SUFFIX
# Name we use for a column we know doesn't exist in the data, to address a Vega-Lite rendering bug
# where empty charts need x, y encodings set in order to take up space.
NON_EXISTENT_COLUMN_NAME = "DOES_NOT_EXIST" + PROTECTION_SUFFIX
class ArrowAltairMixin:
@gather_metrics("line_chart")
def line_chart(
self,
data: Data = None,
*,
x: str | None = None,
y: str | Sequence[str] | None = None,
color: str | Color | list[Color] | None = None,
width: int = 0,
height: int = 0,
use_container_width: bool = True,
) -> DeltaGenerator:
"""Display a line chart.
This is syntax-sugar around ``st.altair_chart``. The main difference
is this command uses the data's own column and indices to figure out
the chart's spec. As a result this is easier to use for many "just plot
this" scenarios, while being less customizable.
If ``st.line_chart`` does not guess the data specification
correctly, try specifying your desired chart using ``st.altair_chart``.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, dict or None
Data to be plotted.
x : str or None
Column name to use for the x-axis. If None, uses the data index for the x-axis.
y : str, Sequence of str, or None
Column name(s) to use for the y-axis. If a Sequence of strings,
draws several series on the same chart by melting your wide-format
table into a long-format table behind the scenes. If None, draws
the data of all remaining columns as data series.
color : str, tuple, Sequence of str, Sequence of tuple, or None
The color to use for different lines in this chart.
For a line chart with just one line, this can be:
* None, to use the default color.
* A hex string like "#ffaa00" or "#ffaa0088".
* An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
For a line chart with multiple lines, where the dataframe is in
long format (that is, y is None or just one column), this can be:
* None, to use the default colors.
* The name of a column in the dataset. Data points will be grouped
into lines of the same color based on the value of this column.
In addition, if the values in this column match one of the color
formats above (hex string or color tuple), then that color will
be used.
For example: if the dataset has 1000 rows, but this column only
contains the values "adult", "child", and "baby", then those 1000
datapoints will be grouped into three lines whose colors will be
automatically selected from the default palette.
But, if for the same 1000-row dataset, this column contained
the values "#ffaa00", "#f0f", "#0000ff", then then those 1000
datapoints would still be grouped into three lines, but their
colors would be "#ffaa00", "#f0f", "#0000ff" this time around.
For a line chart with multiple lines, where the dataframe is in
wide format (that is, y is a Sequence of columns), this can be:
* None, to use the default colors.
* A list of string colors or color tuples to be used for each of
the lines in the chart. This list should have the same length
as the number of y values (e.g. ``color=["#fd0", "#f0f", "#04f"]``
for three lines).
width : int
The chart width in pixels. If 0, selects the width automatically.
height : int
The chart height in pixels. If 0, selects the height automatically.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over the width argument.
Examples
--------
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
>>>
>>> st.line_chart(chart_data)
.. output::
https://doc-line-chart.streamlit.app/
height: 440px
You can also choose different columns to use for x and y, as well as set
the color dynamically based on a 3rd column (assuming your dataframe is in
long format):
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(
... {
... "col1": np.random.randn(20),
... "col2": np.random.randn(20),
... "col3": np.random.choice(["A", "B", "C"], 20),
... }
... )
>>>
>>> st.line_chart(chart_data, x="col1", y="col2", color="col3")
.. output::
https://doc-line-chart1.streamlit.app/
height: 440px
Finally, if your dataframe is in wide format, you can group multiple
columns under the y argument to show multiple lines with different
colors:
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["col1", "col2", "col3"])
>>>
>>> st.line_chart(
... chart_data, x="col1", y=["col2", "col3"], color=["#FF0000", "#0000FF"] # Optional
... )
.. output::
https://doc-line-chart2.streamlit.app/
height: 440px
"""
proto = ArrowVegaLiteChartProto()
chart, add_rows_metadata = _generate_chart(
chart_type=ChartType.LINE,
data=data,
x_from_user=x,
y_from_user=y,
color_from_user=color,
size_from_user=None,
width=width,
height=height,
)
marshall(proto, chart, use_container_width, theme="streamlit")
return self.dg._enqueue(
"arrow_line_chart", proto, add_rows_metadata=add_rows_metadata
)
@gather_metrics("area_chart")
def area_chart(
self,
data: Data = None,
*,
x: str | None = None,
y: str | Sequence[str] | None = None,
color: str | Color | list[Color] | None = None,
width: int = 0,
height: int = 0,
use_container_width: bool = True,
) -> DeltaGenerator:
"""Display an area chart.
This is syntax-sugar around ``st.altair_chart``. The main difference
is this command uses the data's own column and indices to figure out
the chart's spec. As a result this is easier to use for many "just plot
this" scenarios, while being less customizable.
If ``st.area_chart`` does not guess the data specification
correctly, try specifying your desired chart using ``st.altair_chart``.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, or dict
Data to be plotted.
x : str or None
Column name to use for the x-axis. If None, uses the data index for the x-axis.
y : str, Sequence of str, or None
Column name(s) to use for the y-axis. If a Sequence of strings,
draws several series on the same chart by melting your wide-format
table into a long-format table behind the scenes. If None, draws
the data of all remaining columns as data series.
color : str, tuple, Sequence of str, Sequence of tuple, or None
The color to use for different series in this chart.
For an area chart with just 1 series, this can be:
* None, to use the default color.
* A hex string like "#ffaa00" or "#ffaa0088".
* An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
For an area chart with multiple series, where the dataframe is in
long format (that is, y is None or just one column), this can be:
* None, to use the default colors.
* The name of a column in the dataset. Data points will be grouped
into series of the same color based on the value of this column.
In addition, if the values in this column match one of the color
formats above (hex string or color tuple), then that color will
be used.
For example: if the dataset has 1000 rows, but this column only
contains the values "adult", "child", and "baby", then those 1000
datapoints will be grouped into three series whose colors will be
automatically selected from the default palette.
But, if for the same 1000-row dataset, this column contained
the values "#ffaa00", "#f0f", "#0000ff", then then those 1000
datapoints would still be grouped into 3 series, but their
colors would be "#ffaa00", "#f0f", "#0000ff" this time around.
For an area chart with multiple series, where the dataframe is in
wide format (that is, y is a Sequence of columns), this can be:
* None, to use the default colors.
* A list of string colors or color tuples to be used for each of
the series in the chart. This list should have the same length
as the number of y values (e.g. ``color=["#fd0", "#f0f", "#04f"]``
for three lines).
width : int
The chart width in pixels. If 0, selects the width automatically.
height : int
The chart height in pixels. If 0, selects the height automatically.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over the width argument.
Examples
--------
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
>>>
>>> st.area_chart(chart_data)
.. output::
https://doc-area-chart.streamlit.app/
height: 440px
You can also choose different columns to use for x and y, as well as set
the color dynamically based on a 3rd column (assuming your dataframe is in
long format):
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(
... {
... "col1": np.random.randn(20),
... "col2": np.random.randn(20),
... "col3": np.random.choice(["A", "B", "C"], 20),
... }
... )
>>>
>>> st.area_chart(chart_data, x="col1", y="col2", color="col3")
.. output::
https://doc-area-chart1.streamlit.app/
height: 440px
Finally, if your dataframe is in wide format, you can group multiple
columns under the y argument to show multiple series with different
colors:
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["col1", "col2", "col3"])
>>>
>>> st.area_chart(
... chart_data, x="col1", y=["col2", "col3"], color=["#FF0000", "#0000FF"] # Optional
... )
.. output::
https://doc-area-chart2.streamlit.app/
height: 440px
"""
proto = ArrowVegaLiteChartProto()
chart, add_rows_metadata = _generate_chart(
chart_type=ChartType.AREA,
data=data,
x_from_user=x,
y_from_user=y,
color_from_user=color,
size_from_user=None,
width=width,
height=height,
)
marshall(proto, chart, use_container_width, theme="streamlit")
return self.dg._enqueue(
"arrow_area_chart", proto, add_rows_metadata=add_rows_metadata
)
@gather_metrics("bar_chart")
def bar_chart(
self,
data: Data = None,
*,
x: str | None = None,
y: str | Sequence[str] | None = None,
color: str | Color | list[Color] | None = None,
width: int = 0,
height: int = 0,
use_container_width: bool = True,
) -> DeltaGenerator:
"""Display a bar chart.
This is syntax-sugar around ``st.altair_chart``. The main difference
is this command uses the data's own column and indices to figure out
the chart's spec. As a result this is easier to use for many "just plot
this" scenarios, while being less customizable.
If ``st.bar_chart`` does not guess the data specification
correctly, try specifying your desired chart using ``st.altair_chart``.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, or dict
Data to be plotted.
x : str or None
Column name to use for the x-axis. If None, uses the data index for the x-axis.
y : str, Sequence of str, or None
Column name(s) to use for the y-axis. If a Sequence of strings,
draws several series on the same chart by melting your wide-format
table into a long-format table behind the scenes. If None, draws
the data of all remaining columns as data series.
color : str, tuple, Sequence of str, Sequence of tuple, or None
The color to use for different series in this chart.
For a bar chart with just one series, this can be:
* None, to use the default color.
* A hex string like "#ffaa00" or "#ffaa0088".
* An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
For a bar chart with multiple series, where the dataframe is in
long format (that is, y is None or just one column), this can be:
* None, to use the default colors.
* The name of a column in the dataset. Data points will be grouped
into series of the same color based on the value of this column.
In addition, if the values in this column match one of the color
formats above (hex string or color tuple), then that color will
be used.
For example: if the dataset has 1000 rows, but this column only
contains the values "adult", "child", and "baby", then those 1000
datapoints will be grouped into three series whose colors will be
automatically selected from the default palette.
But, if for the same 1000-row dataset, this column contained
the values "#ffaa00", "#f0f", "#0000ff", then then those 1000
datapoints would still be grouped into 3 series, but their
colors would be "#ffaa00", "#f0f", "#0000ff" this time around.
For a bar chart with multiple series, where the dataframe is in
wide format (that is, y is a Sequence of columns), this can be:
* None, to use the default colors.
* A list of string colors or color tuples to be used for each of
the series in the chart. This list should have the same length
as the number of y values (e.g. ``color=["#fd0", "#f0f", "#04f"]``
for three lines).
width : int
The chart width in pixels. If 0, selects the width automatically.
height : int
The chart height in pixels. If 0, selects the height automatically.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over the width argument.
Examples
--------
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
>>>
>>> st.bar_chart(chart_data)
.. output::
https://doc-bar-chart.streamlit.app/
height: 440px
You can also choose different columns to use for x and y, as well as set
the color dynamically based on a 3rd column (assuming your dataframe is in
long format):
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(
... {
... "col1": list(range(20)) * 3,
... "col2": np.random.randn(60),
... "col3": ["A"] * 20 + ["B"] * 20 + ["C"] * 20,
... }
... )
>>>
>>> st.bar_chart(chart_data, x="col1", y="col2", color="col3")
.. output::
https://doc-bar-chart1.streamlit.app/
height: 440px
Finally, if your dataframe is in wide format, you can group multiple
columns under the y argument to show multiple series with different
colors:
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(
... {"col1": list(range(20)), "col2": np.random.randn(20), "col3": np.random.randn(20)}
... )
>>>
>>> st.bar_chart(
... chart_data, x="col1", y=["col2", "col3"], color=["#FF0000", "#0000FF"] # Optional
... )
.. output::
https://doc-bar-chart2.streamlit.app/
height: 440px
"""
proto = ArrowVegaLiteChartProto()
chart, add_rows_metadata = _generate_chart(
chart_type=ChartType.BAR,
data=data,
x_from_user=x,
y_from_user=y,
color_from_user=color,
size_from_user=None,
width=width,
height=height,
)
marshall(proto, chart, use_container_width, theme="streamlit")
return self.dg._enqueue(
"arrow_bar_chart", proto, add_rows_metadata=add_rows_metadata
)
@gather_metrics("scatter_chart")
def scatter_chart(
self,
data: Data = None,
*,
x: str | None = None,
y: str | Sequence[str] | None = None,
color: str | Color | list[Color] | None = None,
size: str | float | int | None = None,
width: int = 0,
height: int = 0,
use_container_width: bool = True,
) -> DeltaGenerator:
"""Display a scatterplot chart.
This is syntax-sugar around ``st.altair_chart``. The main difference
is this command uses the data's own column and indices to figure out
the chart's spec. As a result this is easier to use for many "just plot
this" scenarios, while being less customizable.
If ``st.scatter_chart`` does not guess the data specification correctly,
try specifying your desired chart using ``st.altair_chart``.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, dict or None
Data to be plotted.
x : str or None
Column name to use for the x-axis. If None, uses the data index for the x-axis.
y : str, Sequence of str, or None
Column name(s) to use for the y-axis. If a Sequence of strings,
draws several series on the same chart by melting your wide-format
table into a long-format table behind the scenes. If None, draws
the data of all remaining columns as data series.
color : str, tuple, Sequence of str, Sequence of tuple, or None
The color of the circles representing each datapoint.
This can be:
* None, to use the default color.
* A hex string like "#ffaa00" or "#ffaa0088".
* An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
* The name of a column in the dataset where the color of that
datapoint will come from.
If the values in this column are in one of the color formats
above (hex string or color tuple), then that color will be used.
Otherwise, the color will be automatically picked from the
default palette.
For example: if the dataset has 1000 rows, but this column only
contains the values "adult", "child", and "baby", then those 1000
datapoints be shown using three colors from the default palette.
But if this column only contains floats or ints, then those
1000 datapoints will be shown using a colors from a continuous
color gradient.
Finally, if this column only contains the values "#ffaa00",
"#f0f", "#0000ff", then then each of those 1000 datapoints will
be assigned "#ffaa00", "#f0f", or "#0000ff" as appropriate.
If the dataframe is in wide format (that is, y is a Sequence of
columns), this can also be:
* A list of string colors or color tuples to be used for each of
the series in the chart. This list should have the same length
as the number of y values (e.g. ``color=["#fd0", "#f0f", "#04f"]``
for three series).
size : str, float, int, or None
The size of the circles representing each point.
This can be:
* A number like 100, to specify a single size to use for all
datapoints.
* The name of the column to use for the size. This allows each
datapoint to be represented by a circle of a different size.
width : int
The chart width in pixels. If 0, selects the width automatically.
height : int
The chart height in pixels. If 0, selects the height automatically.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over the width argument.
Examples
--------
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
>>>
>>> st.scatter_chart(chart_data)
.. output::
https://doc-scatter-chart.streamlit.app/
height: 440px
You can also choose different columns to use for x and y, as well as set
the color dynamically based on a 3rd column (assuming your dataframe is in
long format):
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["col1", "col2", "col3"])
>>> chart_data['col4'] = np.random.choice(['A','B','C'], 20)
>>>
>>> st.scatter_chart(
... chart_data,
... x='col1',
... y='col2',
... color='col4',
... size='col3',
... )
.. output::
https://doc-scatter-chart1.streamlit.app/
height: 440px
Finally, if your dataframe is in wide format, you can group multiple
columns under the y argument to show multiple series with different
colors:
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 4), columns=["col1", "col2", "col3", "col4"])
>>>
>>> st.scatter_chart(
... chart_data,
... x='col1',
... y=['col2', 'col3'],
... size='col4',
... color=['#FF0000', '#0000FF'], # Optional
... )
.. output::
https://doc-scatter-chart2.streamlit.app/
height: 440px
"""
proto = ArrowVegaLiteChartProto()
chart, add_rows_metadata = _generate_chart(
chart_type=ChartType.SCATTER,
data=data,
x_from_user=x,
y_from_user=y,
color_from_user=color,
size_from_user=size,
width=width,
height=height,
)
marshall(proto, chart, use_container_width, theme="streamlit")
return self.dg._enqueue(
"arrow_scatter_chart", proto, add_rows_metadata=add_rows_metadata
)
@gather_metrics("altair_chart")
def altair_chart(
self,
altair_chart: alt.Chart,
use_container_width: bool = False,
theme: Literal["streamlit"] | None = "streamlit",
) -> DeltaGenerator:
"""Display a chart using the Altair library.
Parameters
----------
altair_chart : altair.Chart
The Altair chart object to display.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over Altair's native ``width`` value.
theme : "streamlit" or None
The theme of the chart. Currently, we only support "streamlit" for the Streamlit
defined design or None to fallback to the default behavior of the library.
Example
-------
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>> import altair as alt
>>>
>>> chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
>>>
>>> c = (
... alt.Chart(chart_data)
... .mark_circle()
... .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"])
... )
>>>
>>> st.altair_chart(c, use_container_width=True)
.. output::
https://doc-vega-lite-chart.streamlit.app/
height: 300px
Examples of Altair charts can be found at
https://altair-viz.github.io/gallery/.
"""
if theme != "streamlit" and theme != None:
raise StreamlitAPIException(
f'You set theme="{theme}" while Streamlit charts only support theme=”streamlit” or theme=None to fallback to the default library theme.'
)
proto = ArrowVegaLiteChartProto()
marshall(
proto,
altair_chart,
use_container_width=use_container_width,
theme=theme,
)
return self.dg._enqueue("arrow_vega_lite_chart", proto)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def _is_date_column(df: pd.DataFrame, name: str | None) -> bool:
"""True if the column with the given name stores datetime.date values.
This function just checks the first value in the given column, so
it's meaningful only for columns whose values all share the same type.
Parameters
----------
df : pd.DataFrame
name : str
The column name
Returns
-------
bool
"""
if name is None:
return False
column = df[name]
if column.size == 0:
return False
return isinstance(column.iloc[0], date)
def _melt_data(
df: pd.DataFrame,
columns_to_leave_alone: list[str],
columns_to_melt: list[str] | None,
new_y_column_name: str,
new_color_column_name: str,
) -> pd.DataFrame:
"""Converts a wide-format dataframe to a long-format dataframe."""
import pandas as pd
from pandas.api.types import infer_dtype
melted_df = pd.melt(
df,
id_vars=columns_to_leave_alone,
value_vars=columns_to_melt,
var_name=new_color_column_name,
value_name=new_y_column_name,
)
y_series = melted_df[new_y_column_name]
if (
y_series.dtype == "object"
and "mixed" in infer_dtype(y_series)
and len(y_series.unique()) > 100
):
raise StreamlitAPIException(
"The columns used for rendering the chart contain too many values with mixed types. Please select the columns manually via the y parameter."
)
# Arrow has problems with object types after melting two different dtypes
# pyarrow.lib.ArrowTypeError: "Expected a <TYPE> object, got a object"
fixed_df = type_util.fix_arrow_incompatible_column_types(
melted_df,
selected_columns=[
*columns_to_leave_alone,
new_color_column_name,
new_y_column_name,
],
)
return fixed_df
def prep_data(
df: pd.DataFrame,
x_column: str | None,
y_column_list: list[str],
color_column: str | None,
size_column: str | None,
) -> tuple[pd.DataFrame, str | None, str | None, str | None, str | None]:
"""Prepares the data for charting. This is also used in add_rows.
Returns the prepared dataframe and the new names of the x column (taking the index reset into
consideration) and y, color, and size columns.
"""
# If y is provided, but x is not, we'll use the index as x.
# So we need to pull the index into its own column.
x_column = _maybe_reset_index_in_place(df, x_column, y_column_list)
# Drop columns we're not using.
selected_data = _drop_unused_columns(
df, x_column, color_column, size_column, *y_column_list
)
# Maybe convert color to Vega colors.
_maybe_convert_color_column_in_place(selected_data, color_column)
# Make sure all columns have string names.
(
x_column,
y_column_list,
color_column,
size_column,
) = _convert_col_names_to_str_in_place(
selected_data, x_column, y_column_list, color_column, size_column
)
# Maybe melt data from wide format into long format.
melted_data, y_column, color_column = _maybe_melt(
selected_data, x_column, y_column_list, color_column, size_column
)
# Return the data, but also the new names to use for x, y, and color.
return melted_data, x_column, y_column, color_column, size_column
def _generate_chart(
chart_type: ChartType,
data: Data | None,
x_from_user: str | None = None,
y_from_user: str | Sequence[str] | None = None,
color_from_user: str | Color | list[Color] | None = None,
size_from_user: str | float | None = None,
width: int = 0,
height: int = 0,
) -> tuple[alt.Chart, AddRowsMetadata]:
"""Function to use the chart's type, data columns and indices to figure out the chart's spec."""
import altair as alt
df = type_util.convert_anything_to_df(data, ensure_copy=True)
# From now on, use "df" instead of "data". Deleting "data" to guarantee we follow this.
del data
# Convert arguments received from the user to things Vega-Lite understands.
# Get name of column to use for x.
x_column = _parse_x_column(df, x_from_user)
# Get name of columns to use for y.
y_column_list = _parse_y_columns(df, y_from_user, x_column)
# Get name of column to use for color, or constant value to use. Any/both could be None.
color_column, color_value = _parse_generic_column(df, color_from_user)
# Get name of column to use for size, or constant value to use. Any/both could be None.
size_column, size_value = _parse_generic_column(df, size_from_user)
# Store some info so we can use it in add_rows.
add_rows_metadata = AddRowsMetadata(
# The last index of df so we can adjust the input df in add_rows:
last_index=last_index_for_melted_dataframes(df),
# This is the input to prep_data (except for the df):
columns=dict(
x_column=x_column,
y_column_list=y_column_list,
color_column=color_column,
size_column=size_column,
),
)
# At this point, all foo_column variables are either None/empty or contain actual
# columns that are guaranteed to exist.
df, x_column, y_column, color_column, size_column = prep_data(
df, x_column, y_column_list, color_column, size_column
)
# At this point, x_column is only None if user did not provide one AND df is empty.
# Create a Chart with x and y encodings.
chart = alt.Chart(
data=df,
mark=chart_type.value["mark_type"],
width=width,
height=height,
).encode(
x=_get_x_encoding(df, x_column, x_from_user, chart_type),
y=_get_y_encoding(df, y_column, y_from_user),
)
# Set up opacity encoding.
opacity_enc = _get_opacity_encoding(chart_type, color_column)
if opacity_enc is not None:
chart = chart.encode(opacity=opacity_enc)
# Set up color encoding.
color_enc = _get_color_encoding(
df, color_value, color_column, y_column_list, color_from_user
)
if color_enc is not None:
chart = chart.encode(color=color_enc)
# Set up size encoding.