-
Notifications
You must be signed in to change notification settings - Fork 605
/
Copy pathplotly.py
3164 lines (2609 loc) · 95.1 KB
/
plotly.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
"""
Plotly plots.
| Copyright 2017-2024, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
from collections import defaultdict
import itertools
import logging
import os
import warnings
import numpy as np
from PIL import ImageColor
import plotly.colors as pc
import plotly.express as px
import plotly.graph_objects as go
import eta.core.utils as etau
import fiftyone.core.context as foc
import fiftyone.core.labels as fol
import fiftyone.core.utils as fou
from .base import Plot, InteractivePlot, ResponsivePlot
from .utils import (
best_fit_line,
parse_lines_inputs,
parse_locations,
parse_scatter_inputs,
)
logger = logging.getLogger(__name__)
_DEFAULT_LAYOUT = dict(
template="ggplot2", margin={"r": 0, "t": 30, "l": 0, "b": 0}
)
_DEFAULT_LINE_COLOR = "#FF6D04"
_DEFAULT_CONTINUOUS_COLORSCALE = "viridis"
_MAX_LABEL_TRACES = 25
def plot_confusion_matrix(
confusion_matrix,
labels,
ids=None,
samples=None,
eval_key=None,
gt_field=None,
pred_field=None,
colorscale="oranges",
log_colorscale=False,
title=None,
**kwargs,
):
"""Plots a confusion matrix.
If ``ids`` are provided, this method returns a :class:`InteractiveHeatmap`
that you can attach to an App session via its
:attr:`fiftyone.core.session.Session.plots` attribute, which will
automatically sync the session's view with the currently selected cells in
the confusion matrix.
Args:
confusion_matrix: a ``num_true x num_preds`` confusion matrix
labels: a ``max(num_true, num_preds)`` array-like of class labels
ids (None): an array-like of same shape as ``confusion_matrix`` whose
elements are array-likes of label IDs corresponding to each cell
samples (None): the :class:`fiftyone.core.collections.SampleCollection`
for which the confusion matrix was generated. Only used when
``ids`` are also provided to update an attached session
eval_key (None): the evaluation key of the evaluation
gt_field (None): the name of the ground truth field
pred_field (None): the name of the predictions field
colorscale ("oranges"): a plotly colorscale to use. See
https://plotly.com/python/colorscales for options
log_colorscale (False): whether to apply the colorscale on a log scale.
This is useful to better visualize variations in smaller values
when large values are also present
title (None): a title for the plot
**kwargs: optional keyword arguments for
:meth:`plotly:plotly.graph_objects.Figure.update_layout`
Returns:
one of the following
- a :class:`InteractiveHeatmap`, if ``ids`` are provided
- a :class:`PlotlyNotebookPlot`, if no ``ids`` are provided and you
are working in a Jupyter notebook
- a plotly figure, otherwise
"""
if log_colorscale:
maxval = confusion_matrix.max()
colorscale = _to_log_colorscale(colorscale, maxval)
if ids is None:
return _plot_confusion_matrix_static(
confusion_matrix,
labels,
colorscale=colorscale,
title=title,
gt_field=gt_field,
pred_field=pred_field,
**kwargs,
)
return _plot_confusion_matrix_interactive(
confusion_matrix,
labels,
ids,
samples=samples,
eval_key=eval_key,
gt_field=gt_field,
pred_field=pred_field,
colorscale=colorscale,
title=title,
**kwargs,
)
def _plot_confusion_matrix_static(
confusion_matrix,
labels,
colorscale=None,
title=None,
gt_field=None,
pred_field=None,
**kwargs,
):
confusion_matrix = np.asarray(confusion_matrix)
num_rows, num_cols = confusion_matrix.shape
zlim = [0, confusion_matrix.max()]
truth = gt_field or "truth"
predicted = pred_field or "predicted"
hover_lines = [
"<b>count: %{z:d}</b>",
f"{truth}: %{{y}}",
f"{predicted}: %{{x}}",
]
hovertemplate = "<br>".join(hover_lines) + "<extra></extra>"
xlabels = labels[:num_cols]
ylabels = labels[:num_rows]
# Flip data so plot will have the standard descending diagonal
# Flipping the yaxis via `autorange="reversed"` isn't an option because
# screenshots don't seem to respect that setting...
confusion_matrix = np.flip(confusion_matrix, axis=0)
ylabels = np.flip(ylabels)
heatmap = go.Heatmap(
x=xlabels,
y=ylabels,
z=confusion_matrix,
zmin=zlim[0],
zmax=zlim[1],
colorbar=dict(lenmode="fraction", len=1),
colorscale=colorscale,
hovertemplate=hovertemplate,
)
figure = go.Figure(heatmap)
figure.update_layout(
xaxis=dict(range=[-0.5, num_cols - 0.5], constrain="domain"),
yaxis=dict(
range=[-0.5, num_rows - 0.5],
constrain="domain",
scaleanchor="x",
scaleratio=1,
),
title=title,
)
figure.update_layout(**_DEFAULT_LAYOUT)
figure.update_layout(**kwargs)
if foc.is_jupyter_context():
figure = PlotlyNotebookPlot(figure)
return figure
def _plot_confusion_matrix_interactive(
confusion_matrix,
labels,
ids,
samples=None,
eval_key=None,
gt_field=None,
pred_field=None,
colorscale=None,
title=None,
**kwargs,
):
confusion_matrix = np.asarray(confusion_matrix)
ids = np.asarray(ids)
num_rows, num_cols = confusion_matrix.shape
zlim = [0, confusion_matrix.max()]
if samples is not None and eval_key is not None:
if gt_field is None or pred_field is None:
eval_info = samples.get_evaluation_info(eval_key)
gt_field = eval_info.config.gt_field
pred_field = eval_info.config.pred_field
label_type = samples._get_label_field_type(gt_field)
use_patches = issubclass(label_type, (fol.Detections, fol.Polylines))
else:
use_patches = False
if gt_field is not None and pred_field is not None:
label_fields = [gt_field, pred_field]
else:
label_fields = None
xlabels = labels[:num_cols]
ylabels = labels[:num_rows]
# Flip data so plot will have the standard descending diagonal
# Flipping the yaxis via `autorange="reversed"` isn't an option because
# screenshots don't seem to respect that setting...
confusion_matrix = np.flip(confusion_matrix, axis=0)
ids = np.flip(ids, axis=0)
ylabels = np.flip(ylabels)
if use_patches:
selection_mode = "patches"
init_fcn = lambda view: view.to_evaluation_patches(eval_key)
else:
selection_mode = "select"
init_fcn = None
plot = InteractiveHeatmap(
confusion_matrix,
ids,
xlabels=xlabels,
ylabels=ylabels,
zlim=zlim,
gt_field=gt_field,
pred_field=pred_field,
colorscale=colorscale,
link_type="labels",
init_view=samples,
label_fields=label_fields,
selection_mode=selection_mode,
init_fcn=init_fcn,
)
plot.update_layout(**_DEFAULT_LAYOUT)
plot.update_layout(title=title, **kwargs)
return plot
def plot_regressions(
ytrue,
ypred,
samples=None,
ids=None,
labels=None,
sizes=None,
classes=None,
gt_field=None,
pred_field=None,
figure=None,
best_fit_label=None,
marker_size=None,
title=None,
labels_title=None,
sizes_title=None,
show_colorbar_title=None,
**kwargs,
):
"""Plots the given regression results.
If IDs are provided and you are working in a notebook environment with the
default plotly backend, this method returns an :class:`InteractiveScatter`
plot that you can attach to an App session via its
:attr:`fiftyone.core.session.Session.plots` attribute, which will
automatically sync the session's view with the currently selected points in
the plot.
Args:
ytrue: an array-like of ground truth values
ypred: an array-like of predicted values
samples (None): the :class:`fiftyone.core.collections.SampleCollection`
for which the results were generated. Only used by the "plotly"
backend when IDs are provided
ids (None): an array-like of IDs corresponding to the regressions
labels (None): data to use to color the points. Can be any of the
following:
- the name of a sample field or ``embedded.field.name`` of
``samples`` from which to extract numeric or string values
- a :class:`fiftyone.core.expressions.ViewExpression` defining
numeric or string values to compute from ``samples`` via
:meth:`fiftyone.core.collections.SampleCollection.values`
- an array-like of numeric or string values
- a list of array-likes of numeric or string values, if
``link_field`` refers to frames
sizes (None): data to use to scale the sizes of the points. Can be any
of the following:
- the name of a sample field or ``embedded.field.name`` of
``samples`` from which to extract numeric values
- a :class:`fiftyone.core.expressions.ViewExpression` defining
numeric values to compute from ``samples`` via
:meth:`fiftyone.core.collections.SampleCollection.values`
- an array-like of numeric values
- a list of array-likes of numeric or string values, if
``link_field`` refers to frames
classes (None): a list of classes whose points to plot. Only applicable
when ``labels`` contains strings. If provided, the element order of
this list also controls the z-order and legend order of multitrace
plots (first class is rendered first, and thus on the bottom, and
appears first in the legend)
gt_field (None): the name of the ground truth field
pred_field (None): the name of the predictions field
figure (None): a :class:`plotly:plotly.graph_objects.Figure` to which
to add the plot
best_fit_label (None): a custom legend label for the best fit line
marker_size (None): the marker size to use. If ``sizes`` are provided,
this value is used as a reference to scale the sizes of all points
title (None): a title for the plot
labels_title (None): a title string to use for ``labels`` in the
tooltip and the colorbar title. By default, if ``labels`` is a
field name, this name will be used, otherwise the colorbar will not
have a title and the tooltip will use "label"
sizes_title (None): a title string to use for ``sizes`` in the tooltip.
By default, if ``sizes`` is a field name, this name will be used,
otherwise the tooltip will use "size"
show_colorbar_title (None): whether to show the colorbar title. By
default, a title will be shown only if a value was passed to
``labels_title`` or an appropriate default can be inferred from
the ``labels`` parameter
**kwargs: optional keyword arguments for
:meth:`plotly:plotly.graph_objects.Figure.update_layout`
Returns:
one of the following
- a :class:`InteractiveScatter`, if IDs are provided
- a :class:`PlotlyNotebookPlot`, if no IDs are provided but you are
working in a Jupyter notebook
- a plotly figure, otherwise
"""
if (
samples is not None
and gt_field is not None
and samples._is_frame_field(gt_field)
):
link_field = "frames"
else:
link_field = None
points = np.stack([ytrue, ypred], axis=-1)
labels_title, sizes_title, _ = _parse_titles(
labels, labels_title, sizes, sizes_title, None
)
(
points,
ids,
labels,
sizes,
_,
classes,
categorical,
) = parse_scatter_inputs(
points,
samples=samples,
ids=ids,
link_field=link_field,
labels=labels,
sizes=sizes,
classes=classes,
)
xline, yline, best_fit_label = best_fit_line(points, label=best_fit_label)
xlabel = gt_field if gt_field is not None else "Ground truth"
ylabel = pred_field if pred_field is not None else "Predictions"
if figure is None:
figure = go.Figure()
best_fit = go.Scatter(
x=xline, y=yline, mode="lines", line_color="black", name=best_fit_label
)
figure.add_trace(best_fit)
figure.update_layout(xaxis_title=xlabel, yaxis_title=ylabel)
if labels is not None and (
not categorical or len(classes) > _MAX_LABEL_TRACES
):
# Move legend so it doesn't interfere with colorbar
figure.update_layout(
legend=dict(y=0.99, x=0.01, yanchor="top", xanchor="left")
)
return scatterplot(
points,
samples=samples,
ids=ids,
link_field=link_field,
labels=labels,
sizes=sizes,
figure=figure,
marker_size=marker_size,
title=title,
trace_title="regressions",
labels_title=labels_title,
sizes_title=sizes_title,
show_colorbar_title=show_colorbar_title,
axis_equal=True,
**kwargs,
)
def plot_pr_curve(
precision,
recall,
thresholds=None,
label=None,
style="area",
figure=None,
title=None,
**kwargs,
):
"""Plots a precision-recall (PR) curve.
Args:
precision: an array-like of precision values
recall: an array-like of recall values
thresholds (None): an array-like of decision thresholds
label (None): a label for the curve
style ("area"): a plot style to use. Supported values are
``("area", "line")``
figure (None): a :class:`plotly:plotly.graph_objects.Figure` to which
to add the plot
title (None): a title for the plot
**kwargs: optional keyword arguments for
:meth:`plotly:plotly.graph_objects.Figure.update_layout`
Returns:
one of the following
- a :class:`PlotlyNotebookPlot`, if you are working in a Jupyter
notebook
- a plotly figure, otherwise
"""
if style not in ("line", "area"):
msg = "Unsupported style '%s'; using 'area' instead" % style
warnings.warn(msg)
style = "area"
if figure is None:
figure = go.Figure()
params = {"mode": "lines", "line_color": _DEFAULT_LINE_COLOR}
if style == "area":
params["fill"] = "tozeroy"
hover_lines = [
"recall: %{x:.3f}",
"precision: %{y:.3f}",
]
if thresholds is not None:
hover_lines.append("threshold: %{customdata:.3f}")
hovertemplate = "<br>".join(hover_lines) + "<extra></extra>"
figure.add_trace(
go.Scatter(
x=recall,
y=precision,
hovertemplate=hovertemplate,
customdata=thresholds,
**params,
)
)
# Add 50/50 line
figure.add_shape(
type="line", x0=0, x1=1, y0=1, y1=0, line=dict(dash="dash")
)
if title is None and label is not None:
title = label
figure.update_layout(
xaxis=dict(range=[0, 1], constrain="domain"),
yaxis=dict(
range=[0, 1], constrain="domain", scaleanchor="x", scaleratio=1
),
xaxis_title="Recall",
yaxis_title="Precision",
title=title,
)
figure.update_layout(**_DEFAULT_LAYOUT)
figure.update_layout(**kwargs)
if foc.is_jupyter_context():
figure = PlotlyNotebookPlot(figure)
return figure
def plot_pr_curves(
precisions,
recall,
classes,
thresholds=None,
figure=None,
title=None,
**kwargs,
):
"""Plots a set of per-class precision-recall (PR) curves.
Args:
precisions: a ``num_classes x num_recalls`` array-like of per-class
precision values
recall: an array-like of recall values
classes: the list of classes
thresholds (None): a ``num_classes x num_recalls`` array-like of
decision thresholds
figure (None): a :class:`plotly:plotly.graph_objects.Figure` to which
to add the plots
title (None): a title for the plot
**kwargs: optional keyword arguments for
:meth:`plotly:plotly.graph_objects.Figure.update_layout`
Returns:
one of the following
- a :class:`PlotlyNotebookPlot`, if you are working in a Jupyter
notebook
- a plotly figure, otherwise
"""
if figure is None:
figure = go.Figure()
# Add 50/50 line
figure.add_shape(
type="line", line=dict(dash="dash"), x0=0, x1=1, y0=1, y1=0
)
hover_lines = [
"<b>class: %{text}</b>",
"recall: %{x:.3f}",
"precision: %{y:.3f}",
]
if thresholds is not None:
hover_lines.append("threshold: %{customdata:.3f}")
hovertemplate = "<br>".join(hover_lines) + "<extra></extra>"
# Plot in descending order of AP
avg_precisions = np.mean(precisions, axis=1)
inds = np.argsort(-avg_precisions) # negative for descending order
colors = _get_qualitative_colors(len(inds))
for idx, color in zip(inds, colors):
precision = precisions[idx]
_class = classes[idx]
avg_precision = avg_precisions[idx]
label = "%s (AP = %.3f)" % (_class, avg_precision)
if thresholds is not None:
customdata = thresholds[idx]
else:
customdata = None
line = go.Scatter(
x=recall,
y=precision,
name=label,
mode="lines",
line_color=color,
text=np.full(recall.shape, _class),
hovertemplate=hovertemplate,
customdata=customdata,
)
figure.add_trace(line)
figure.update_layout(
xaxis=dict(range=[0, 1], constrain="domain"),
yaxis=dict(
range=[0, 1], constrain="domain", scaleanchor="x", scaleratio=1
),
xaxis_title="Recall",
yaxis_title="Precision",
title=title,
)
figure.update_layout(**_DEFAULT_LAYOUT)
figure.update_layout(**kwargs)
if foc.is_jupyter_context():
figure = PlotlyNotebookPlot(figure)
return figure
def plot_roc_curve(
fpr,
tpr,
thresholds=None,
roc_auc=None,
style="area",
figure=None,
title=None,
**kwargs,
):
"""Plots a receiver operating characteristic (ROC) curve.
Args:
fpr: an array-like of false positive rates
tpr: an array-like of true positive rates
thresholds (None): an array-like of decision thresholds
roc_auc (None): the area under the ROC curve
style ("area"): a plot style to use. Supported values are
``("area", "line")``
figure (None): a :class:`plotly:plotly.graph_objects.Figure` to which
to add the plot
title (None): a title for the plot
**kwargs: optional keyword arguments for
:meth:`plotly:plotly.graph_objects.Figure.update_layout`
Returns:
one of the following
- a :class:`PlotlyNotebookPlot`, if you are working in a Jupyter
notebook
- a plotly figure, otherwise
"""
if style not in ("line", "area"):
msg = "Unsupported style '%s'; using 'area' instead" % style
warnings.warn(msg)
style = "area"
if figure is None:
figure = go.Figure()
params = {"mode": "lines", "line_color": _DEFAULT_LINE_COLOR}
if style == "area":
params["fill"] = "tozeroy"
hover_lines = ["fpr: %{x:.3f}", "tpr: %{y:.3f}"]
if thresholds is not None:
hover_lines.append("threshold: %{customdata:.3f}")
hovertemplate = "<br>".join(hover_lines) + "<extra></extra>"
figure.add_trace(
go.Scatter(
x=fpr,
y=tpr,
hovertemplate=hovertemplate,
customdata=thresholds,
**params,
)
)
# Add 50/50 line
figure.add_shape(
type="line", line=dict(dash="dash"), x0=0, x1=1, y0=0, y1=1
)
if title is None and roc_auc is not None:
title = dict(text="AUC: %.5f" % roc_auc, x=0.5, xanchor="center")
figure.update_layout(
xaxis=dict(range=[0, 1], constrain="domain"),
yaxis=dict(
range=[0, 1], constrain="domain", scaleanchor="x", scaleratio=1
),
xaxis_title="False positive rate",
yaxis_title="True positive rate",
title=title,
)
figure.update_layout(**_DEFAULT_LAYOUT)
figure.update_layout(**kwargs)
if foc.is_jupyter_context():
figure = PlotlyNotebookPlot(figure)
return figure
def lines(
x=None,
y=None,
samples=None,
ids=None,
link_field=None,
sizes=None,
labels=None,
colors=None,
marker_size=None,
figure=None,
title=None,
xaxis_title=None,
yaxis_title=None,
sizes_title=None,
axis_equal=False,
**kwargs,
):
"""Plots the given lines(s) data.
You can attach plots generated by this method to an App session via its
:attr:`fiftyone.core.session.Session.plots` attribute, which will
automatically sync the session's view with the currently selected points in
the plot. To enable this functionality, you must pass ``samples`` to this
method.
You can use the ``sizes`` parameter to scale the sizes of the points.
Args:
x (None): the x data to plot. Can be any of the following:
- an array-like of values
- a ``num_lines x n`` array-like or list of length ``num_lines``
of array-likes of values for multiple line traces
- the name of a sample field or ``embedded.field.name`` of
``samples`` from which to extract values for a single line
- the name of a frame field or ``frames.embedded.field.name`` of
``samples`` from which to extract values for per-sample line
traces
- a :class:`fiftyone.core.expressions.ViewExpression` that
resolves to a list (one line plot) or list of lists (multiple
line plots) of numeric values to compute from ``samples`` via
:meth:`fiftyone.core.collections.SampleCollection.values`
y (None): the y data to plot. Can be any of the following:
- an array-like of values
- a ``num_lines x n`` array-like or list of length ``num_lines``
of array-likes of values for multiple line traces
- the name of a sample field or ``embedded.field.name`` of
``samples`` from which to extract values for a single line
- the name of a frame field or ``frames.embedded.field.name`` of
``samples`` from which to extract values for per-sample line
traces
- a :class:`fiftyone.core.expressions.ViewExpression` that
resolves to a list (one line plot) or list of lists (multiple
line plots) of numeric values to compute from ``samples`` via
:meth:`fiftyone.core.collections.SampleCollection.values`
samples (None): the :class:`fiftyone.core.collections.SampleCollection`
whose data is being visualized
ids (None): an array-like of IDs of same shape as ``y``. If not
provided but ``samples`` are provided, the appropriate IDs will be
extracted from the samples
link_field (None): a field of ``samples`` whose data corresponds to
``y``. Can be any of the following:
- ``None``, if the line data correspond to samples (single trace)
or frames (multiple traces)
- ``"frames"``, if the line data correspond to frames (multiple
traces). This option exists only for consistency with other
plotting methods; in practice, it will be automatically
inferred whenever multiple traces are being plotted
- the name of a :class:`fiftyone.core.labels.Label` field, if the
line data correspond to the labels in this field
sizes (None): data to use to scale the sizes of the points. Can be any
of the following:
- an array-like of numeric values of same shape as ``y``
- the name of a sample field (single trace) or frame field
(multiple traces) from which to extract numeric values
- a :class:`fiftyone.core.expressions.ViewExpression` defining
sample-level (single trace) or frame-level (multiple traces)
numeric values to compute from ``samples`` via
:meth:`fiftyone.core.collections.SampleCollection.values`
labels (None): a name or list of names for the line traces
colors (None): a list of colors to use for the line traces. See
https://plotly.com/python/colorscales for options
marker_size (None): the marker size to use. If ``sizes`` are provided,
this value is used as a reference to scale the sizes of all points
figure (None): a :class:`plotly:plotly.graph_objects.Figure` to which
to add the plot
title (None): a title for the plot
xaxis_title (None): an x-axis title
yaxis_title (None): a y-axis title
sizes_title (None): a title string to use for ``sizes`` in the tooltip.
By default, if ``sizes`` is a field name, this name will be used,
otherwise the tooltip will use "size"
axis_equal (False): whether to set the axes to equal scale
**kwargs: optional keyword arguments for
:meth:`plotly:plotly.graph_objects.Figure.update_layout`
Returns:
one of the following
- an :class:`InteractiveScatter`, when IDs are available
- a :class:`PlotlyNotebookPlot`, if you're working in a Jupyter
notebook but the above conditions aren't met
- a plotly figure, otherwise
"""
if sizes is not None and sizes_title is None:
if etau.is_str(sizes):
sizes_title = sizes.rsplit(".", 1)[-1]
else:
sizes_title = "size"
x, y, ids, link_field, labels, sizes, is_frames = parse_lines_inputs(
x=x,
y=y,
samples=samples,
ids=ids,
link_field=link_field,
labels=labels,
sizes=sizes,
)
if is_frames:
showlegend = True
else:
showlegend = labels[0] is not None
if xaxis_title is not None:
xtitle = xaxis_title.rsplit(".", 1)[-1]
else:
xtitle = "x"
if yaxis_title is not None:
ytitle = yaxis_title.rsplit(".", 1)[-1]
else:
ytitle = "y"
hover_lines = ["%s: %%{x}" % xtitle, "%s: %%{y}" % ytitle]
if sizes[0] is not None:
hover_lines.append("%s: %%{marker.size}" % sizes_title)
if marker_size is None:
marker_size = 15 # max marker size
try:
sizeref = 0.5 * max(itertools.chain(*sizes)) / marker_size
except ValueError:
sizeref = 1
if ids[0] is not None:
hover_lines.append("ID: %{customdata}")
hovertemplate = "<br>".join(hover_lines) + "<extra></extra>"
colors = _get_qualitative_colors(len(y), colors=colors)
traces = []
for _x, _y, _i, _s, _l, _c in zip(x, y, ids, sizes, labels, colors):
marker = {}
if _s is not None:
marker.update(
dict(size=_s, sizemode="diameter", sizeref=sizeref, sizemin=4)
)
elif marker_size is not None:
marker.update(dict(size=marker_size))
traces.append(
go.Scatter(
x=_x,
y=_y,
customdata=_i,
mode="lines+markers",
line_color=_c,
marker=marker,
hovertemplate=hovertemplate,
name=_l,
showlegend=showlegend,
)
)
if figure is None:
figure = go.Figure()
figure.add_traces(traces)
figure.update_layout(**_DEFAULT_LAYOUT)
figure.update_layout(
title=title,
xaxis_title=xaxis_title,
yaxis_title=yaxis_title,
**kwargs,
)
if axis_equal:
figure.update_layout(yaxis_scaleanchor="x")
if ids is None:
if foc.is_jupyter_context():
return PlotlyNotebookPlot(figure)
return figure
(
link_type,
label_fields,
selection_mode,
init_fcn,
) = InteractiveScatter.recommend_link_type(
label_field=link_field,
samples=samples,
)
return InteractiveScatter(
figure,
link_type=link_type,
init_view=samples,
label_fields=label_fields,
selection_mode=selection_mode,
init_fcn=init_fcn,
)
def scatterplot(
points,
samples=None,
ids=None,
link_field=None,
labels=None,
sizes=None,
edges=None,
classes=None,
figure=None,
multi_trace=None,
marker_size=None,
colorscale=None,
log_colorscale=False,
title=None,
trace_title=None,
labels_title=None,
sizes_title=None,
edges_title=None,
show_colorbar_title=None,
axis_equal=False,
**kwargs,
):
"""Generates an interactive scatterplot of the given points.
You can attach plots generated by this method to an App session via its
:attr:`fiftyone.core.session.Session.plots` attribute, which will
automatically sync the session's view with the currently selected points in
the plot. To enable this functionality, you must pass ``samples`` to this
method.
This method supports 2D or 3D visualizations, but interactive point
selection is only available in 2D.
You can use the ``labels`` parameters to define a coloring for the points,
and you can use the ``sizes`` parameter to scale the sizes of the points.
Args:
points: a ``num_points x num_dims`` array-like of points
samples (None): the :class:`fiftyone.core.collections.SampleCollection`
whose data is being visualized
ids (None): an array-like of IDs corresponding to the points. If not
provided but ``samples`` are provided, the appropriate IDs will be
extracted from the samples
link_field (None): a field of ``samples`` whose data corresponds to
``points``. Can be any of the following:
- None, if the points correspond to samples
- ``"frames"``, if the points correspond to frames
- the name of a :class:`fiftyone.core.labels.Label` field, if the
points correspond to the labels in this field
labels (None): data to use to color the points. Can be any of the
following:
- the name of a sample field or ``embedded.field.name`` of
``samples`` from which to extract numeric or string values
- a :class:`fiftyone.core.expressions.ViewExpression` defining
numeric or string values to compute from ``samples`` via
:meth:`fiftyone.core.collections.SampleCollection.values`
- an array-like of numeric or string values
- a list of array-likes of numeric or string values, if
``link_field`` refers to frames and/or a label list field like
:class:`fiftyone.core.labels.Detections`
sizes (None): data to use to scale the sizes of the points. Can be any
of the following:
- the name of a sample field or ``embedded.field.name`` of
``samples`` from which to extract numeric values
- a :class:`fiftyone.core.expressions.ViewExpression` defining
numeric values to compute from ``samples`` via