-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathbasedatatypes.py
4112 lines (3421 loc) · 134 KB
/
basedatatypes.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
import collections
import re
import six
from six import string_types
import warnings
from contextlib import contextmanager
from copy import deepcopy, copy
from pprint import PrettyPrinter
from .optional_imports import get_module
from . import offline as pyo
from _plotly_utils.basevalidators import (
CompoundValidator, CompoundArrayValidator, BaseDataValidator,
BaseValidator, LiteralValidator
)
from . import animation
from .callbacks import (Points, BoxSelector, LassoSelector,
InputDeviceState)
from .utils import ElidedPrettyPrinter
from .validators import (DataValidator, LayoutValidator, FramesValidator)
# Optional imports
# ----------------
np = get_module('numpy')
# Create Undefined sentinel value
# - Setting a property to None removes any existing value
# - Setting a property to Undefined leaves existing value unmodified
Undefined = object()
class BaseFigure(object):
"""
Base class for all figure types (both widget and non-widget)
"""
_bracket_re = re.compile('^(.*)\[(\d+)\]$')
# Constructor
# -----------
def __init__(self,
data=None,
layout_plotly=None,
frames=None,
skip_invalid=False):
"""
Construct a BaseFigure object
Parameters
----------
data
One of:
- A list or tuple of trace objects (or dicts that can be coerced
into trace objects)
- If `data` is a dict that contains a 'data',
'layout', or 'frames' key then these values are used to
construct the figure.
- If `data` is a `BaseFigure` instance then the `data`, `layout`,
and `frames` properties are extracted from the input figure
layout_plotly
The plotly layout dict.
Note: this property is named `layout_plotly` rather than `layout`
to deconflict it with the `layout` constructor parameter of the
`widgets.DOMWidget` ipywidgets class, as the `BaseFigureWidget`
class is a subclass of both BaseFigure and widgets.DOMWidget.
If the `data` property is a BaseFigure instance, or a dict that
contains a 'layout' key, then this property is ignored.
frames
A list or tuple of `plotly.graph_objs.Frame` objects (or dicts
that can be coerced into Frame objects)
If the `data` property is a BaseFigure instance, or a dict that
contains a 'frames' key, then this property is ignored.
skip_invalid: bool
If True, invalid properties in the figure specification will be
skipped silently. If False (default) invalid properties in the
figure specification will result in a ValueError
Raises
------
ValueError
if a property in the specification of data, layout, or frames
is invalid AND skip_invalid is False
"""
super(BaseFigure, self).__init__()
# Assign layout_plotly to layout
# ------------------------------
# See docstring note for explanation
layout = layout_plotly
# Subplot properties
# ------------------
# These properties are used by the tools.make_subplots logic.
# We initialize them to None here, before checking if the input data
# object is a BaseFigure, or a dict with _grid_str and _grid_ref
# properties, in which case we bring over the _grid* properties of
# the input
self._grid_str = None
self._grid_ref = None
# Handle case where data is a Figure or Figure-like dict
# ------------------------------------------------------
if isinstance(data, BaseFigure):
# Bring over subplot fields
self._grid_str = data._grid_str
self._grid_ref = data._grid_ref
# Extract data, layout, and frames
data, layout, frames = data.data, data.layout, data.frames
elif (isinstance(data, dict)
and ('data' in data or 'layout' in data or 'frames' in data)):
# Bring over subplot fields
self._grid_str = data.get('_grid_str', None)
self._grid_ref = data.get('_grid_ref', None)
# Extract data, layout, and frames
data, layout, frames = (data.get('data', None),
data.get('layout', None),
data.get('frames', None))
# Handle data (traces)
# --------------------
# ### Construct data validator ###
# This is the validator that handles importing sequences of trace
# objects
self._data_validator = DataValidator(set_uid=True)
# ### Import traces ###
data = self._data_validator.validate_coerce(data,
skip_invalid=skip_invalid)
# ### Save tuple of trace objects ###
self._data_objs = data
# ### Import clone of trace properties ###
# The _data property is a list of dicts containing the properties
# explicitly set by the user for each trace.
self._data = [deepcopy(trace._props) for trace in data]
# ### Create data defaults ###
# _data_defaults is a tuple of dicts, one for each trace. When
# running in a widget context, these defaults are populated with
# all property values chosen by the Plotly.js library that
# aren't explicitly specified by the user.
#
# Note: No property should exist in both the _data and
# _data_defaults for the same trace.
self._data_defaults = [{} for _ in data]
# ### Reparent trace objects ###
for trace_ind, trace in enumerate(data):
# By setting the trace's parent to be this figure, we tell the
# trace object to use the figure's _data and _data_defaults
# dicts to get/set it's properties, rather than using the trace
# object's internal _orphan_props dict.
trace._parent = self
# We clear the orphan props since the trace no longer needs then
trace._orphan_props.clear()
# Set trace index
trace._trace_ind = trace_ind
# Layout
# ------
# ### Construct layout validator ###
# This is the validator that handles importing Layout objects
self._layout_validator = LayoutValidator()
# ### Import Layout ###
self._layout_obj = self._layout_validator.validate_coerce(
layout, skip_invalid=skip_invalid)
# ### Import clone of layout properties ###
self._layout = deepcopy(self._layout_obj._props)
# ### Initialize layout defaults dict ###
self._layout_defaults = {}
# ### Reparent layout object ###
self._layout_obj._orphan_props.clear()
self._layout_obj._parent = self
# Frames
# ------
# ### Construct frames validator ###
# This is the validator that handles importing sequences of frame
# objects
self._frames_validator = FramesValidator()
# ### Import frames ###
self._frame_objs = self._frames_validator.validate_coerce(
frames, skip_invalid=skip_invalid)
# Note: Because frames are not currently supported in the widget
# context, we don't need to follow the pattern above and create
# _frames and _frame_defaults properties and then reparent the
# frames. The figure doesn't need to be notified of
# changes to the properties in the frames object hierarchy.
# Context manager
# ---------------
# ### batch mode indicator ###
# Flag that indicates whether we're currently inside a batch_*()
# context
self._in_batch_mode = False
# ### Batch trace edits ###
# Dict from trace indexes to trace edit dicts. These trace edit dicts
# are suitable as `data` elements of Plotly.animate, but not
# the Plotly.update (See `_build_update_params_from_batch`)
#
# type: typ.Dict[int, typ.Dict[str, typ.Any]]
self._batch_trace_edits = {}
# ### Batch layout edits ###
# Dict from layout properties to new layout values. This dict is
# directly suitable for use in Plotly.animate and Plotly.update
# type: typ.Dict[str, typ.Any]
self._batch_layout_edits = {}
# Animation property validators
# -----------------------------
self._animation_duration_validator = animation.DurationValidator()
self._animation_easing_validator = animation.EasingValidator()
# Magic Methods
# -------------
def __reduce__(self):
"""
Custom implementation of reduce is used to support deep copying
and pickling
"""
props = self.to_dict()
props['_grid_str'] = self._grid_str
props['_grid_ref'] = self._grid_ref
return (self.__class__,
(props,))
def __setitem__(self, prop, value):
# Normalize prop
# --------------
# Convert into a property tuple
orig_prop = prop
prop = BaseFigure._str_to_dict_path(prop)
# Handle empty case
# -----------------
if len(prop) == 0:
raise KeyError(orig_prop)
# Handle scalar case
# ------------------
# e.g. ('foo',)
elif len(prop) == 1:
# ### Unwrap scalar tuple ###
prop = prop[0]
if prop == 'data':
self.data = value
elif prop == 'layout':
self.layout = value
elif prop == 'frames':
self.frames = value
else:
raise KeyError(prop)
# Handle non-scalar case
# ----------------------
# e.g. ('foo', 1)
else:
res = self
for p in prop[:-1]:
res = res[p]
res[prop[-1]] = value
def __setattr__(self, prop, value):
"""
Parameters
----------
prop : str
The name of a direct child of this object
value
New property value
Returns
-------
None
"""
if prop.startswith('_') or hasattr(self, prop):
# Let known properties and private properties through
super(BaseFigure, self).__setattr__(prop, value)
else:
# Raise error on unknown public properties
raise AttributeError(prop)
def __getitem__(self, prop):
# Normalize prop
# --------------
# Convert into a property tuple
orig_prop = prop
prop = BaseFigure._str_to_dict_path(prop)
# Handle scalar case
# ------------------
# e.g. ('foo',)
if len(prop) == 1:
# Unwrap scalar tuple
prop = prop[0]
if prop == 'data':
return self._data_validator.present(self._data_objs)
elif prop == 'layout':
return self._layout_validator.present(self._layout_obj)
elif prop == 'frames':
return self._frames_validator.present(self._frame_objs)
else:
raise KeyError(orig_prop)
# Handle non-scalar case
# ----------------------
# e.g. ('foo', 1)
else:
res = self
for p in prop:
res = res[p]
return res
def __iter__(self):
return iter(('data', 'layout', 'frames'))
def __contains__(self, prop):
return prop in ('data', 'layout', 'frames')
def __eq__(self, other):
if not isinstance(other, BaseFigure):
# Require objects to both be BaseFigure instances
return False
else:
# Compare plotly_json representations
# Use _vals_equal instead of `==` to handle cases where
# underlying dicts contain numpy arrays
return BasePlotlyType._vals_equal(self.to_plotly_json(),
other.to_plotly_json())
def __repr__(self):
"""
Customize Figure representation when displayed in the
terminal/notebook
"""
repr_str = BasePlotlyType._build_repr_for_class(
props=self.to_plotly_json(),
class_name=self.__class__.__name__)
return repr_str
def update(self, dict1=None, **kwargs):
"""
Update the properties of the figure with a dict and/or with
keyword arguments.
This recursively updates the structure of the figure
object with the values in the input dict / keyword arguments.
Parameters
----------
dict1 : dict
Dictionary of properties to be updated
kwargs :
Keyword/value pair of properties to be updated
Examples
--------
>>> import plotly.graph_objs as go
>>> fig = go.Figure(data=[{'y': [1, 2, 3]}])
>>> fig.update(data=[{'y': [4, 5, 6]}])
>>> fig.to_plotly_json()
{'data': [{'type': 'scatter',
'uid': 'e86a7c7a-346a-11e8-8aa8-a0999b0c017b',
'y': array([4, 5, 6], dtype=int32)}],
'layout': {}}
>>> fig = go.Figure(layout={'xaxis':
... {'color': 'green',
... 'range': [0, 1]}})
>>> fig.update({'layout': {'xaxis': {'color': 'pink'}}})
>>> fig.to_plotly_json()
{'data': [],
'layout': {'xaxis':
{'color': 'pink',
'range': [0, 1]}}}
Returns
-------
BaseFigure
Updated figure
"""
with self.batch_update():
for d in [dict1, kwargs]:
if d:
for k, v in d.items():
if self[k] == ():
# existing data or frames property is empty
# In this case we accept the v as is.
if k == 'data':
self.add_traces(v)
else:
# Accept v
self[k] = v
else:
BaseFigure._perform_update(self[k], v)
return self
# Data
# ----
@property
def data(self):
"""
The `data` property is a tuple of the figure's trace objects
Returns
-------
tuple[BaseTraceType]
"""
return self['data']
@data.setter
def data(self, new_data):
# Validate new_data
# -----------------
err_header = ('The data property of a figure may only be assigned '
'a list or tuple that contains a permutation of a '
'subset of itself\n')
# ### Check valid input type ###
if not isinstance(new_data, (list, tuple)):
err_msg = (err_header + ' Received value with type {typ}'
.format(typ=type(new_data)))
raise ValueError(err_msg)
# ### Check valid element types ###
for trace in new_data:
if not isinstance(trace, BaseTraceType):
err_msg = (
err_header + ' Received element value of type {typ}'
.format(typ=type(trace)))
raise ValueError(err_msg)
# ### Check UIDs ###
# Require that no new uids are introduced
orig_uids = [_trace['uid'] for _trace in self._data]
new_uids = [trace.uid for trace in new_data]
invalid_uids = set(new_uids).difference(set(orig_uids))
if invalid_uids:
err_msg = (
err_header + ' Invalid trace(s) with uid(s): {invalid_uids}'
.format(invalid_uids=invalid_uids))
raise ValueError(err_msg)
# ### Check for duplicates in assignment ###
uid_counter = collections.Counter(new_uids)
duplicate_uids = [
uid for uid, count in uid_counter.items() if count > 1
]
if duplicate_uids:
err_msg = (
err_header + ' Received duplicated traces with uid(s): ' +
'{duplicate_uids}'.format(duplicate_uids=duplicate_uids))
raise ValueError(err_msg)
# Remove traces
# -------------
remove_uids = set(orig_uids).difference(set(new_uids))
delete_inds = []
# ### Unparent removed traces ###
for i, _trace in enumerate(self._data):
if _trace['uid'] in remove_uids:
delete_inds.append(i)
# Unparent trace object to be removed
old_trace = self.data[i]
old_trace._orphan_props.update(deepcopy(old_trace._props))
old_trace._parent = None
old_trace._trace_ind = None
# ### Compute trace props / defaults after removal ###
traces_props_post_removal = [t for t in self._data]
traces_prop_defaults_post_removal = [t for t in self._data_defaults]
uids_post_removal = [trace_data['uid'] for trace_data in self._data]
for i in reversed(delete_inds):
del traces_props_post_removal[i]
del traces_prop_defaults_post_removal[i]
del uids_post_removal[i]
# Modify in-place so we don't trigger serialization
del self._data[i]
if delete_inds:
# Update widget, if any
self._send_deleteTraces_msg(delete_inds)
# Move traces
# -----------
# ### Compute new index for each remaining trace ###
new_inds = []
for uid in uids_post_removal:
new_inds.append(new_uids.index(uid))
# ### Compute current index for each remaining trace ###
current_inds = list(range(len(traces_props_post_removal)))
# ### Check whether a move is needed ###
if not all([i1 == i2 for i1, i2 in zip(new_inds, current_inds)]):
# #### Update widget, if any ####
self._send_moveTraces_msg(current_inds, new_inds)
# #### Reorder trace elements ####
# We do so in-place so we don't trigger traitlet property
# serialization for the FigureWidget case
# ##### Remove by curr_inds in reverse order #####
moving_traces_data = []
for ci in reversed(current_inds):
# Push moving traces data to front of list
moving_traces_data.insert(0, self._data[ci])
del self._data[ci]
# #### Sort new_inds and moving_traces_data by new_inds ####
new_inds, moving_traces_data = zip(
*sorted(zip(new_inds, moving_traces_data)))
# #### Insert by new_inds in forward order ####
for ni, trace_data in zip(new_inds, moving_traces_data):
self._data.insert(ni, trace_data)
# ### Update data defaults ###
# There is to front-end syncronization to worry about so this
# operations doesn't need to be in-place
self._data_defaults = [
_trace for i, _trace in sorted(
zip(new_inds, traces_prop_defaults_post_removal))
]
# Update trace objects tuple
self._data_objs = list(new_data)
# Update trace indexes
for trace_ind, trace in enumerate(self._data_objs):
trace._trace_ind = trace_ind
# Restyle
# -------
def plotly_restyle(self, restyle_data, trace_indexes=None, **kwargs):
"""
Perform a Plotly restyle operation on the figure's traces
Parameters
----------
restyle_data : dict
Dict of trace style updates.
Keys are strings that specify the properties to be updated.
Nested properties are expressed by joining successive keys on
'.' characters (e.g. 'marker.color').
Values may be scalars or lists. When values are scalars,
that scalar value is applied to all traces specified by the
`trace_indexes` parameter. When values are lists,
the restyle operation will cycle through the elements
of the list as it cycles through the traces specified by the
`trace_indexes` parameter.
Caution: To use plotly_restyle to update a list property (e.g.
the `x` property of the scatter trace), the property value
should be a scalar list containing the list to update with. For
example, the following command would be used to update the 'x'
property of the first trace to the list [1, 2, 3]
>>> fig.plotly_restyle({'x': [[1, 2, 3]]}, 0)
trace_indexes : int or list of int
Trace index, or list of trace indexes, that the restyle operation
applies to. Defaults to all trace indexes.
Returns
-------
None
"""
# Normalize trace indexes
# -----------------------
trace_indexes = self._normalize_trace_indexes(trace_indexes)
# Handle source_view_id
# ---------------------
# If not None, the source_view_id is the UID of the frontend
# Plotly.js view that initially triggered this restyle operation
# (e.g. the user clicked on the legend to hide a trace). We pass
# this UID along so that the frontend views can determine whether
# they need to apply the restyle operation on themselves.
source_view_id = kwargs.get('source_view_id', None)
# Perform restyle on trace dicts
# ------------------------------
restyle_changes = self._perform_plotly_restyle(restyle_data,
trace_indexes)
if restyle_changes:
# The restyle operation resulted in a change to some trace
# properties, so we dispatch change callbacks and send the
# restyle message to the frontend (if any)
msg_kwargs = ({'source_view_id': source_view_id}
if source_view_id is not None
else {})
self._send_restyle_msg(
restyle_changes,
trace_indexes=trace_indexes,
**msg_kwargs)
self._dispatch_trace_change_callbacks(
restyle_changes, trace_indexes)
def _perform_plotly_restyle(self, restyle_data, trace_indexes):
"""
Perform a restyle operation on the figure's traces data and return
the changes that were applied
Parameters
----------
restyle_data : dict[str, any]
See docstring for plotly_restyle
trace_indexes : list[int]
List of trace indexes that restyle operation applies to
Returns
-------
restyle_changes: dict[str, any]
Subset of restyle_data including only the keys / values that
resulted in a change to the figure's traces data
"""
# Initialize restyle changes
# --------------------------
# This will be a subset of the restyle_data including only the
# keys / values that are changed in the figure's trace data
restyle_changes = {}
# Process each key
# ----------------
for key_path_str, v in restyle_data.items():
# Track whether any of the new values are cause a change in
# self._data
any_vals_changed = False
for i, trace_ind in enumerate(trace_indexes):
if trace_ind >= len(self._data):
raise ValueError(
'Trace index {trace_ind} out of range'.format(
trace_ind=trace_ind))
# Get new value for this particular trace
trace_v = v[i % len(v)] if isinstance(v, list) else v
if trace_v is not Undefined:
# Get trace being updated
trace_obj = self.data[trace_ind]
# Validate key_path_str
if not BaseFigure._is_key_path_compatible(
key_path_str, trace_obj):
trace_class = trace_obj.__class__.__name__
raise ValueError("""
Invalid property path '{key_path_str}' for trace class {trace_class}
""".format(key_path_str=key_path_str, trace_class=trace_class))
# Apply set operation for this trace and thist value
val_changed = BaseFigure._set_in(self._data[trace_ind],
key_path_str,
trace_v)
# Update any_vals_changed status
any_vals_changed = (any_vals_changed or val_changed)
if any_vals_changed:
restyle_changes[key_path_str] = v
return restyle_changes
def _restyle_child(self, child, key_path_str, val):
"""
Process restyle operation on a child trace object
Note: This method name/signature must match the one in
BasePlotlyType. BasePlotlyType objects call their parent's
_restyle_child method without knowing whether their parent is a
BasePlotlyType or a BaseFigure.
Parameters
----------
child : BaseTraceType
Child being restyled
key_path_str : str
A key path string (e.g. 'foo.bar[0]')
val
Restyle value
Returns
-------
None
"""
# Compute trace index
# -------------------
trace_index = child._trace_ind
# Not in batch mode
# -----------------
# Dispatch change callbacks and send restyle message
if not self._in_batch_mode:
send_val = [val]
restyle = {key_path_str: send_val}
self._send_restyle_msg(restyle, trace_indexes=trace_index)
self._dispatch_trace_change_callbacks(restyle, [trace_index])
# In batch mode
# -------------
# Add key_path_str/val to saved batch edits
else:
if trace_index not in self._batch_trace_edits:
self._batch_trace_edits[trace_index] = {}
self._batch_trace_edits[trace_index][key_path_str] = val
def _normalize_trace_indexes(self, trace_indexes):
"""
Input trace index specification and return list of the specified trace
indexes
Parameters
----------
trace_indexes : None or int or list[int]
Returns
-------
list[int]
"""
if trace_indexes is None:
trace_indexes = list(range(len(self.data)))
if not isinstance(trace_indexes, (list, tuple)):
trace_indexes = [trace_indexes]
return list(trace_indexes)
@staticmethod
def _str_to_dict_path(key_path_str):
"""
Convert a key path string into a tuple of key path elements
Parameters
----------
key_path_str : str
Key path string, where nested keys are joined on '.' characters
and array indexes are specified using brackets
(e.g. 'foo.bar[1]')
Returns
-------
tuple[str | int]
"""
if isinstance(key_path_str, string_types) and \
'.' not in key_path_str and \
'[' not in key_path_str:
# Fast path for common case that avoids regular expressions
return (key_path_str,)
elif isinstance(key_path_str, tuple):
# Nothing to do
return key_path_str
else:
# Split string on periods. e.g. 'foo.bar[1]' -> ['foo', 'bar[1]']
key_path = key_path_str.split('.')
# Split out bracket indexes.
# e.g. ['foo', 'bar[1]'] -> ['foo', 'bar', '1']
key_path2 = []
for key in key_path:
match = BaseFigure._bracket_re.match(key)
if match:
key_path2.extend(match.groups())
else:
key_path2.append(key)
# Convert elements to ints if possible.
# e.g. ['foo', 'bar', '0'] -> ['foo', 'bar', 0]
for i in range(len(key_path2)):
try:
key_path2[i] = int(key_path2[i])
except ValueError as _:
pass
return tuple(key_path2)
@staticmethod
def _set_in(d, key_path_str, v):
"""
Set a value in a nested dict using a key path string
(e.g. 'foo.bar[0]')
Parameters
----------
d : dict
Input dict to set property in
key_path_str : str
Key path string, where nested keys are joined on '.' characters
and array indexes are specified using brackets
(e.g. 'foo.bar[1]')
v
New value
Returns
-------
bool
True if set resulted in modification of dict (i.e. v was not
already present at the specified location), False otherwise.
"""
# Validate inputs
# ---------------
assert isinstance(d, dict)
# Compute key path
# ----------------
# Convert the key_path_str into a tuple of key paths
# e.g. 'foo.bar[0]' -> ('foo', 'bar', 0)
key_path = BaseFigure._str_to_dict_path(key_path_str)
# Initialize val_parent
# ---------------------
# This variable will be assigned to the parent of the next key path
# element currently being processed
val_parent = d
# Initialize parent dict or list of value to be assigned
# -----------------------------------------------------
for kp, key_path_el in enumerate(key_path[:-1]):
# Extend val_parent list if needed
if (isinstance(val_parent, list) and
isinstance(key_path_el, int)):
while len(val_parent) <= key_path_el:
val_parent.append(None)
elif (isinstance(val_parent, dict) and
key_path_el not in val_parent):
if isinstance(key_path[kp + 1], int):
val_parent[key_path_el] = []
else:
val_parent[key_path_el] = {}
val_parent = val_parent[key_path_el]
# Assign value to to final parent dict or list
# --------------------------------------------
# ### Get reference to final key path element ###
last_key = key_path[-1]
# ### Track whether assignment alters parent ###
val_changed = False
# v is Undefined
# --------------
# Don't alter val_parent
if v is Undefined:
pass
# v is None
# ---------
# Check whether we can remove key from parent
elif v is None:
if isinstance(val_parent, dict):
if last_key in val_parent:
# Parent is a dict and has last_key as a current key so
# we can pop the key, which alters parent
val_parent.pop(last_key)
val_changed = True
elif isinstance(val_parent, list):
if (isinstance(last_key, int) and
0 <= last_key < len(val_parent)):
# Parent is a list and last_key is a valid index so we
# can set the element value to None
val_parent[last_key] = None
val_changed = True
else:
# Unsupported parent type (numpy array for example)
raise ValueError("""
Cannot remove element of type {typ} at location {raw_key}"""
.format(typ=type(val_parent),
raw_key=key_path_str))
# v is a valid value
# ------------------
# Check whether parent should be updated
else:
if isinstance(val_parent, dict):
if (last_key not in val_parent
or not BasePlotlyType._vals_equal(
val_parent[last_key], v)):
# Parent is a dict and does not already contain the
# value v at key last_key
val_parent[last_key] = v
val_changed = True
elif isinstance(val_parent, list):
if isinstance(last_key, int):
# Extend list with Nones if needed so that last_key is
# in bounds
while len(val_parent) <= last_key:
val_parent.append(None)
if not BasePlotlyType._vals_equal(
val_parent[last_key], v):
# Parent is a list and does not already contain the
# value v at index last_key
val_parent[last_key] = v
val_changed = True
else:
# Unsupported parent type (numpy array for example)
raise ValueError("""
Cannot set element of type {typ} at location {raw_key}"""
.format(typ=type(val_parent),
raw_key=key_path_str))
return val_changed
# Add traces
# ----------
@staticmethod
def _raise_invalid_rows_cols(name, n, invalid):
rows_err_msg = """
If specified, the {name} parameter must be a list or tuple of integers
of length {n} (The number of traces being added)
Received: {invalid}
""".format(name=name, n=n, invalid=invalid)
raise ValueError(rows_err_msg)
@staticmethod
def _validate_rows_cols(name, n, vals):
if vals is None:
pass
elif isinstance(vals, (list, tuple)):
if len(vals) != n:
BaseFigure._raise_invalid_rows_cols(
name=name, n=n, invalid=vals)
if [r for r in vals if not isinstance(r, int)]:
BaseFigure._raise_invalid_rows_cols(
name=name, n=n, invalid=vals)
else:
BaseFigure._raise_invalid_rows_cols(name=name, n=n, invalid=vals)
def add_trace(self, trace, row=None, col=None):
"""
Add a trace to the figure
Parameters
----------
trace : BaseTraceType or dict
Either:
- An instances of a trace classe from the plotly.graph_objs
package (e.g plotly.graph_objs.Scatter, plotly.graph_objs.Bar)
- or a dicts where:
- The 'type' property specifies the trace type (e.g.
'scatter', 'bar', 'area', etc.). If the dict has no 'type'
property then 'scatter' is assumed.
- All remaining properties are passed to the constructor
of the specified trace type.
row : int or None (default)
Subplot row index (starting from 1) for the trace to be added.
Only valid if figure was created using
`plotly.tools.make_subplots`
col : int or None (default)