forked from plotly/plotly.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basedatatypes.py
6321 lines (5341 loc) · 220 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
from __future__ import absolute_import
import collections
from collections import OrderedDict
import re
import six
from six import string_types
import warnings
from contextlib import contextmanager
from copy import deepcopy, copy
import itertools
from functools import reduce
from _plotly_utils.utils import (
_natural_sort_strings,
_get_int_type,
split_multichar,
split_string_positions,
display_string_positions,
chomp_empty_strings,
find_closest_string,
)
from _plotly_utils.exceptions import PlotlyKeyError
from .optional_imports import get_module
import shapeannotation
import subplots
# Create Undefined sentinel value
# - Setting a property to None removes any existing value
# - Setting a property to Undefined leaves existing value unmodified
Undefined = object()
def _len_dict_item(item):
"""
Because a parsed dict path is a tuple containings strings or integers, to
know the length of the resulting string when printing we might need to
convert to a string before calling len on it.
"""
try:
l = len(item)
except TypeError:
try:
l = len("%d" % (item,))
except TypeError:
raise ValueError(
"Cannot find string length of an item that is not string-like nor an integer."
)
return l
def _str_to_dict_path_full(key_path_str):
"""
Convert a key path string into a tuple of key path elements and also
return a tuple of indices marking the beginning of each element in the
string.
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]
tuple [int]
"""
# skip all the parsing if the string is empty
if len(key_path_str):
# split string on ".[]" and filter out empty strings
key_path2 = split_multichar([key_path_str], list(".[]"))
# Split out underscore
# e.g. ['foo', 'bar_baz', '1'] -> ['foo', 'bar', 'baz', '1']
key_path3 = []
underscore_props = BaseFigure._valid_underscore_properties
def _make_hyphen_key(key):
if "_" in key[1:]:
# For valid properties that contain underscores (error_x)
# replace the underscores with hyphens to protect them
# from being split up
for under_prop, hyphen_prop in underscore_props.items():
key = key.replace(under_prop, hyphen_prop)
return key
def _make_underscore_key(key):
return key.replace("-", "_")
key_path2b = list(map(_make_hyphen_key, key_path2))
# Here we want to split up each non-empty string in the list at
# underscores and recombine the strings using chomp_empty_strings so
# that leading, trailing and multiple _ will be preserved
def _split_and_chomp(s):
if not len(s):
return s
s_split = split_multichar([s], list("_"))
# handle key paths like "a_path_", "_another_path", or
# "yet__another_path" by joining extra "_" to the string to the right or
# the empty string if at the end
s_chomped = chomp_empty_strings(s_split, "_", reverse=True)
return s_chomped
# after running _split_and_chomp on key_path2b, it will be a list
# containing strings and lists of strings; concatenate the sublists with
# the list ("lift" the items out of the sublists)
key_path2c = list(
reduce(
lambda x, y: x + y if type(y) == type(list()) else x + [y],
map(_split_and_chomp, key_path2b),
[],
)
)
key_path2d = list(map(_make_underscore_key, key_path2c))
all_elem_idcs = tuple(split_string_positions(list(key_path2d)))
# remove empty strings, and indices pointing to them
key_elem_pairs = list(filter(lambda t: len(t[1]), enumerate(key_path2d)))
key_path3 = [x for _, x in key_elem_pairs]
elem_idcs = [all_elem_idcs[i] for i, _ in key_elem_pairs]
# Convert elements to ints if possible.
# e.g. ['foo', 'bar', '0'] -> ['foo', 'bar', 0]
for i in range(len(key_path3)):
try:
key_path3[i] = int(key_path3[i])
except ValueError as _:
pass
else:
key_path3 = []
elem_idcs = []
return (tuple(key_path3), elem_idcs)
def _remake_path_from_tuple(props):
"""
try to remake a path using the properties in props
"""
if len(props) == 0:
return ""
def _add_square_brackets_to_number(n):
if type(n) == type(int()):
return "[%d]" % (n,)
return n
def _prepend_dot_if_not_number(s):
if not s.startswith("["):
return "." + s
return s
props_all_str = list(map(_add_square_brackets_to_number, props))
props_w_underscore = props_all_str[:1] + list(
map(_prepend_dot_if_not_number, props_all_str[1:])
)
return "".join(props_w_underscore)
def _check_path_in_prop_tree(obj, path, error_cast=None):
"""
obj: the object in which the first property is looked up
path: the path that will be split into properties to be looked up
path can also be a tuple. In this case, it is combined using .
and [] because it is impossible to reconstruct the string fully
in order to give a decent error message.
error_cast: this function walks down the property tree by looking up values
in objects. So this will throw exceptions that are thrown by
__getitem__, but in some cases we are checking the path for a
different reason and would prefer throwing a more relevant
exception (e.g., __getitem__ throws KeyError but __setitem__
throws ValueError for subclasses of BasePlotlyType and
BaseFigure). So the resulting error can be "casted" to the
passed in type, if not None.
returns
an Exception object or None. The caller can raise this
exception to see where the lookup error occurred.
"""
if isinstance(path, tuple):
path = _remake_path_from_tuple(path)
prop, prop_idcs = _str_to_dict_path_full(path)
prev_objs = []
for i, p in enumerate(prop):
arg = ""
prev_objs.append(obj)
try:
obj = obj[p]
except (ValueError, KeyError, IndexError, TypeError) as e:
arg = e.args[0]
if issubclass(e.__class__, TypeError):
# If obj doesn't support subscripting, state that and show the
# (valid) property that gives the object that doesn't support
# subscripting.
if i > 0:
validator = prev_objs[i - 1]._get_validator(prop[i - 1])
arg += """
Invalid value received for the '{plotly_name}' property of {parent_name}
{description}""".format(
parent_name=validator.parent_name,
plotly_name=validator.plotly_name,
description=validator.description(),
)
# In case i is 0, the best we can do is indicate the first
# property in the string as having caused the error
disp_i = max(i - 1, 0)
dict_item_len = _len_dict_item(prop[disp_i])
# if the path has trailing underscores, the prop string will start with "_"
trailing_underscores = ""
if prop[i][0] == "_":
trailing_underscores = " and path has trailing underscores"
# if the path has trailing underscores and the display index is
# one less than the prop index (see above), then we can also
# indicate the offending underscores
if (trailing_underscores != "") and (disp_i != i):
dict_item_len += _len_dict_item(prop[i])
arg += """
Property does not support subscripting%s:
%s
%s""" % (
trailing_underscores,
path,
display_string_positions(
prop_idcs, disp_i, length=dict_item_len, char="^"
),
)
else:
# State that the property for which subscripting was attempted
# is bad and indicate the start of the bad property.
arg += """
Bad property path:
%s
%s""" % (
path,
display_string_positions(
prop_idcs, i, length=_len_dict_item(prop[i]), char="^"
),
)
# Make KeyError more pretty by changing it to a PlotlyKeyError,
# because the Python interpreter has a special way of printing
# KeyError
if isinstance(e, KeyError):
e = PlotlyKeyError()
if error_cast is not None:
e = error_cast()
e.args = (arg,)
return e
return None
def _combine_dicts(dicts):
all_args = dict()
for d in dicts:
for k in d:
all_args[k] = d[k]
return all_args
def _indexing_combinations(dims, alls, product=False):
"""
Gives indexing tuples specified by the coordinates in dims.
If a member of dims is 'all' then it is replaced by the corresponding member
in alls.
If product is True, then the cartesian product of all the indices is
returned, otherwise the zip (that means index lists of mis-matched length
will yield a list of tuples whose length is the length of the shortest
list).
"""
if len(dims) == 0:
# this is because list(itertools.product(*[])) returns [()] which has non-zero
# length!
return []
if len(dims) != len(alls):
raise ValueError(
"Must have corresponding values in alls for each value of dims. Got dims=%s and alls=%s."
% (str(dims), str(alls))
)
r = []
for d, a in zip(dims, alls):
if d == "all":
d = a
elif not isinstance(d, list):
d = [d]
r.append(d)
if product:
return itertools.product(*r)
else:
return zip(*r)
def _is_select_subplot_coordinates_arg(*args):
""" Returns true if any args are lists or the string 'all' """
return any((a == "all") or isinstance(a, list) for a in args)
def _axis_spanning_shapes_docstr(shape_type):
docstr = ""
if shape_type == "hline":
docstr = """
Add a horizontal line to a plot or subplot that extends infinitely in the
x-dimension.
Parameters
----------
y: float or int
A number representing the y coordinate of the horizontal line."""
elif shape_type == "vline":
docstr = """
Add a vertical line to a plot or subplot that extends infinitely in the
y-dimension.
Parameters
----------
x: float or int
A number representing the x coordinate of the vertical line."""
elif shape_type == "hrect":
docstr = """
Add a rectangle to a plot or subplot that extends infinitely in the
x-dimension.
Parameters
----------
y0: float or int
A number representing the y coordinate of one side of the rectangle.
y1: float or int
A number representing the y coordinate of the other side of the rectangle."""
elif shape_type == "vrect":
docstr = """
Add a rectangle to a plot or subplot that extends infinitely in the
y-dimension.
Parameters
----------
x0: float or int
A number representing the x coordinate of one side of the rectangle.
x1: float or int
A number representing the x coordinate of the other side of the rectangle."""
docstr += """
exclude_empty_subplots: Boolean
If True (default) do not place the shape on subplots that have no data
plotted on them.
row: None, int or 'all'
Subplot row for shape indexed starting at 1. If 'all', addresses all rows in
the specified column(s). If both row and col are None, addresses the
first subplot if subplots exist, or the only plot. By default is "all".
col: None, int or 'all'
Subplot column for shape indexed starting at 1. If 'all', addresses all rows in
the specified column(s). If both row and col are None, addresses the
first subplot if subplots exist, or the only plot. By default is "all".
annotation: dict or new_plotly.graph_objects.layout.Annotation. If dict(),
it is interpreted as describing an annotation. The annotation is
placed relative to the shape based on annotation_position (see
below) unless its x or y value has been specified for the annotation
passed here. xref and yref are always the same as for the added
shape and cannot be overridden."""
if shape_type in ["hline", "vline"]:
docstr += """
annotation_position: a string containing optionally ["top", "bottom"]
and ["left", "right"] specifying where the text should be anchored
to on the line. Example positions are "bottom left", "right top",
"right", "bottom". If an annotation is added but annotation_position is
not specified, this defaults to "top right"."""
elif shape_type in ["hrect", "vrect"]:
docstr += """
annotation_position: a string containing optionally ["inside", "outside"], ["top", "bottom"]
and ["left", "right"] specifying where the text should be anchored
to on the rectangle. Example positions are "outside top left", "inside
bottom", "right", "inside left", "inside" ("outside" is not supported). If
an annotation is added but annotation_position is not specified this
defaults to "inside top right"."""
docstr += """
annotation_*: any parameters to go.layout.Annotation can be passed as
keywords by prefixing them with "annotation_". For example, to specify the
annotation text "example" you can pass annotation_text="example" as a
keyword argument.
**kwargs:
Any named function parameters that can be passed to 'add_shape',
except for x0, x1, y0, y1 or type."""
return docstr
def _generator(i):
""" "cast" an iterator to a generator """
for x in i:
yield x
class BaseFigure(object):
"""
Base class for all figure types (both widget and non-widget)
"""
_bracket_re = re.compile(r"^(.*)\[(\d+)\]$")
_valid_underscore_properties = {
"error_x": "error-x",
"error_y": "error-y",
"error_z": "error-z",
"copy_xstyle": "copy-xstyle",
"copy_ystyle": "copy-ystyle",
"copy_zstyle": "copy-zstyle",
"paper_bgcolor": "paper-bgcolor",
"plot_bgcolor": "plot-bgcolor",
}
_set_trace_uid = False
_allow_disable_validation = True
# Constructor
# -----------
def __init__(
self, data=None, layout_plotly=None, frames=None, skip_invalid=False, **kwargs
):
"""
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 new_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 `new_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
"""
from .validators import DataValidator, LayoutValidator, FramesValidator
super(BaseFigure, self).__init__()
# Initialize validation
self._validate = kwargs.pop("_validate", True)
# 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=self._set_trace_uid)
# ### Import traces ###
data = self._data_validator.validate_coerce(
data, skip_invalid=skip_invalid, _validate=self._validate
)
# ### 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, _validate=self._validate
)
# ### 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
# Config
# ------
# Pass along default config to the front end. For now this just
# ensures that the new_plotly domain url gets passed to the front end.
# In the future we can extend this to allow the user to supply
# arbitrary config options like in new_plotly.offline.plot/iplot. But
# this will require a fair amount of testing to determine which
# options are compatible with FigureWidget.
from plotly.offline.offline import _get_jconfig
self._config = _get_jconfig(None)
# 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`)
self._batch_trace_edits = OrderedDict()
# ### Batch layout edits ###
# Dict from layout properties to new layout values. This dict is
# directly suitable for use in Plotly.animate and Plotly.update
self._batch_layout_edits = OrderedDict()
# Animation property validators
# -----------------------------
from . import animation
self._animation_duration_validator = animation.DurationValidator()
self._animation_easing_validator = animation.EasingValidator()
# Template
# --------
# ### Check for default template ###
self._initialize_layout_template()
# Process kwargs
# --------------
for k, v in kwargs.items():
err = _check_path_in_prop_tree(self, k)
if err is None:
self[k] = v
elif not skip_invalid:
type_err = TypeError("invalid Figure property: {}".format(k))
type_err.args = (
type_err.args[0]
+ """
%s"""
% (err.args[0],),
)
raise type_err
# 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:
err = _check_path_in_prop_tree(self, orig_prop, error_cast=ValueError)
if err is not None:
raise err
res = self
for p in prop[:-1]:
res = res[p]
res._validate = self._validate
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:
err = _check_path_in_prop_tree(self, orig_prop, error_cast=PlotlyKeyError)
if err is not None:
raise err
res = self
for p in prop:
res = res[p]
return res
def __iter__(self):
return iter(("data", "layout", "frames"))
def __contains__(self, prop):
prop = BaseFigure._str_to_dict_path(prop)
if prop[0] not in ("data", "layout", "frames"):
return False
elif len(prop) == 1:
return True
else:
return prop[1:] in self[prop[0]]
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
"""
props = self.to_plotly_json()
# Elide template
template_props = props.get("layout", {}).get("template", {})
if template_props:
props["layout"]["template"] = "..."
repr_str = BasePlotlyType._build_repr_for_class(
props=props, class_name=self.__class__.__name__
)
return repr_str
def _repr_html_(self):
"""
Customize html representation
"""
bundle = self._repr_mimebundle_()
if "text/html" in bundle:
return bundle["text/html"]
else:
return self.to_html(full_html=False, include_plotlyjs="cdn")
def _repr_mimebundle_(self, include=None, exclude=None, validate=True, **kwargs):
"""
Return mimebundle corresponding to default renderer.
"""
import plotly.io as pio
renderer_str = pio.renderers.default
renderers = pio._renderers.renderers
renderer_names = renderers._validate_coerce_renderers(renderer_str)
renderers_list = [renderers[name] for name in renderer_names]
from plotly.io._utils import validate_coerce_fig_to_dict
from plotly.io._renderers import MimetypeRenderer
fig_dict = validate_coerce_fig_to_dict(self, validate)
# Mimetype renderers
bundle = {}
for renderer in renderers_list:
if isinstance(renderer, MimetypeRenderer):
bundle.update(renderer.to_mimebundle(fig_dict))
return bundle
def _ipython_display_(self):
"""
Handle rich display of figures in ipython contexts
"""
import plotly.io as pio
if pio.renderers.render_on_display and pio.renderers.default:
pio.show(self)
else:
print(repr(self))
def update(self, dict1=None, overwrite=False, **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
overwrite: bool
If True, overwrite existing properties. If False, apply updates
to existing properties recursively, preserving existing
properties that are not specified in the update operation.
kwargs :
Keyword/value pair of properties to be updated
Examples
--------
>>> import new_plotly.graph_objs as go
>>> fig = go.Figure(data=[{'y': [1, 2, 3]}])
>>> fig.update(data=[{'y': [4, 5, 6]}]) # doctest: +ELLIPSIS
Figure(...)
>>> fig.to_plotly_json() # doctest: +SKIP
{'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'}}}) # doctest: +ELLIPSIS
Figure(...)
>>> fig.to_plotly_json() # doctest: +SKIP
{'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():
update_target = self[k]
if update_target == () or overwrite:
if k == "data":
# Overwrite all traces as special due to
# restrictions on trace assignment
self.data = ()
self.add_traces(v)
else:
# Accept v
self[k] = v
elif (
isinstance(update_target, BasePlotlyType)
and isinstance(v, (dict, BasePlotlyType))
) or (
isinstance(update_target, tuple)
and isinstance(update_target[0], BasePlotlyType)
):
BaseFigure._perform_update(self[k], v)
else:
self[k] = v
return self
def pop(self, key, *args):
"""
Remove the value associated with the specified key and return it
Parameters
----------
key: str
Property name
dflt
The default value to return if key was not found in figure
Returns
-------
value
The removed value that was previously associated with key
Raises
------
KeyError
If key is not in object and no dflt argument specified
"""
# Handle default
if key not in self and args:
return args[0]
elif key in self:
val = self[key]
self[key] = None
return val
else:
raise KeyError(key)
# 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 \n"
"a list or tuple that contains a permutation of a "
"subset of itself.\n"
)
# ### Treat None as empty ###
if new_data is None:
new_data = ()
# ### 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 trace objects ###
# Require that no new traces are introduced
orig_uids = [id(trace) for trace in self.data]
new_uids = [id(trace) for trace in new_data]