forked from plotly/plotly.py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotly.py
More file actions
1852 lines (1543 loc) · 65.8 KB
/
plotly.py
File metadata and controls
1852 lines (1543 loc) · 65.8 KB
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
======
A module that contains the plotly class, a liaison between the user
and ploty's servers.
1. get DEFAULT_PLOT_OPTIONS for options
2. update plot_options with .plotly/ dir
3. update plot_options with _plot_options
4. update plot_options with kwargs!
"""
from __future__ import absolute_import
import copy
import json
import os
import time
import warnings
import webbrowser
import six
import six.moves
from requests.compat import json as _json
from plotly import exceptions, files, session, tools, utils
from plotly.api import v1, v2
from plotly.plotly import chunked_requests
from plotly.grid_objs import Grid, Column
from plotly.dashboard_objs import dashboard_objs as dashboard
# This is imported like this for backwards compat. Careful if changing.
from plotly.config import get_config, get_credentials
__all__ = None
DEFAULT_PLOT_OPTIONS = {
'filename': "plot from API",
'fileopt': "new",
'world_readable': files.FILE_CONTENT[files.CONFIG_FILE]['world_readable'],
'auto_open': files.FILE_CONTENT[files.CONFIG_FILE]['auto_open'],
'validate': True,
'sharing': files.FILE_CONTENT[files.CONFIG_FILE]['sharing']
}
SHARING_ERROR_MSG = (
"Whoops, sharing can only be set to either 'public', 'private', or "
"'secret'."
)
# test file permissions and make sure nothing is corrupted
tools.ensure_local_plotly_files()
# don't break backwards compatibility
def sign_in(username, api_key, **kwargs):
session.sign_in(username, api_key, **kwargs)
try:
# The only way this can succeed is if the user can be authenticated
# with the given, username, api_key, and plotly_api_domain.
v2.users.current()
except exceptions.PlotlyRequestError:
raise exceptions.PlotlyError('Sign in failed.')
update_plot_options = session.update_session_plot_options
def _plot_option_logic(plot_options_from_call_signature):
"""
Given some plot_options as part of a plot call, decide on final options.
Precedence:
1 - Start with DEFAULT_PLOT_OPTIONS
2 - Update each key with ~/.plotly/.config options (tls.get_config)
3 - Update each key with session plot options (set by py.sign_in)
4 - Update each key with plot, iplot call signature options
"""
default_plot_options = copy.deepcopy(DEFAULT_PLOT_OPTIONS)
file_options = tools.get_config_file()
session_options = session.get_session_plot_options()
plot_options_from_call_signature = copy.deepcopy(plot_options_from_call_signature)
# Validate options and fill in defaults w world_readable and sharing
for option_set in [plot_options_from_call_signature,
session_options, file_options]:
utils.validate_world_readable_and_sharing_settings(option_set)
utils.set_sharing_and_world_readable(option_set)
# dynamic defaults
if ('filename' in option_set and
'fileopt' not in option_set):
option_set['fileopt'] = 'overwrite'
user_plot_options = {}
user_plot_options.update(default_plot_options)
user_plot_options.update(file_options)
user_plot_options.update(session_options)
user_plot_options.update(plot_options_from_call_signature)
user_plot_options = {k: v for k, v in user_plot_options.items()
if k in default_plot_options}
return user_plot_options
def iplot(figure_or_data, **plot_options):
"""Create a unique url for this plot in Plotly and open in IPython.
plot_options keyword agruments:
filename (string) -- the name that will be associated with this figure
fileopt ('new' | 'overwrite' | 'extend' | 'append')
- 'new': create a new, unique url for this plot
- 'overwrite': overwrite the file associated with `filename` with this
- 'extend': add additional numbers (data) to existing traces
- 'append': add additional traces to existing data lists
sharing ('public' | 'private' | 'secret') -- Toggle who can view this graph
- 'public': Anyone can view this graph. It will appear in your profile
and can appear in search engines. You do not need to be
logged in to Plotly to view this chart.
- 'private': Only you can view this plot. It will not appear in the
Plotly feed, your profile, or search engines. You must be
logged in to Plotly to view this graph. You can privately
share this graph with other Plotly users in your online
Plotly account and they will need to be logged in to
view this plot.
- 'secret': Anyone with this secret link can view this chart. It will
not appear in the Plotly feed, your profile, or search
engines. If it is embedded inside a webpage or an IPython
notebook, anybody who is viewing that page will be able to
view the graph. You do not need to be logged in to view
this plot.
world_readable (default=True) -- Deprecated: use "sharing".
Make this figure private/public
"""
if 'auto_open' not in plot_options:
plot_options['auto_open'] = False
url = plot(figure_or_data, **plot_options)
if isinstance(figure_or_data, dict):
layout = figure_or_data.get('layout', {})
else:
layout = {}
embed_options = dict()
embed_options['width'] = layout.get('width', '100%')
embed_options['height'] = layout.get('height', 525)
try:
float(embed_options['width'])
except (ValueError, TypeError):
pass
else:
embed_options['width'] = str(embed_options['width']) + 'px'
try:
float(embed_options['height'])
except (ValueError, TypeError):
pass
else:
embed_options['height'] = str(embed_options['height']) + 'px'
return tools.embed(url, **embed_options)
def plot(figure_or_data, validate=True, **plot_options):
"""Create a unique url for this plot in Plotly and optionally open url.
plot_options keyword agruments:
filename (string) -- the name that will be associated with this figure
fileopt ('new' | 'overwrite' | 'extend' | 'append') -- 'new' creates a
'new': create a new, unique url for this plot
'overwrite': overwrite the file associated with `filename` with this
'extend': add additional numbers (data) to existing traces
'append': add additional traces to existing data lists
auto_open (default=True) -- Toggle browser options
True: open this plot in a new browser tab
False: do not open plot in the browser, but do return the unique url
sharing ('public' | 'private' | 'secret') -- Toggle who can view this
graph
- 'public': Anyone can view this graph. It will appear in your profile
and can appear in search engines. You do not need to be
logged in to Plotly to view this chart.
- 'private': Only you can view this plot. It will not appear in the
Plotly feed, your profile, or search engines. You must be
logged in to Plotly to view this graph. You can privately
share this graph with other Plotly users in your online
Plotly account and they will need to be logged in to
view this plot.
- 'secret': Anyone with this secret link can view this chart. It will
not appear in the Plotly feed, your profile, or search
engines. If it is embedded inside a webpage or an IPython
notebook, anybody who is viewing that page will be able to
view the graph. You do not need to be logged in to view
this plot.
world_readable (default=True) -- Deprecated: use "sharing".
Make this figure private/public
"""
figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)
for entry in figure['data']:
if ('type' in entry) and (entry['type'] == 'scattergl'):
continue
for key, val in list(entry.items()):
try:
if len(val) > 40000:
msg = ("Woah there! Look at all those points! Due to "
"browser limitations, the Plotly SVG drawing "
"functions have a hard time "
"graphing more than 500k data points for line "
"charts, or 40k points for other types of charts. "
"Here are some suggestions:\n"
"(1) Use the `plotly.graph_objs.Scattergl` "
"trace object to generate a WebGl graph.\n"
"(2) Trying using the image API to return an image "
"instead of a graph URL\n"
"(3) Use matplotlib\n"
"(4) See if you can create your visualization with "
"fewer data points\n\n"
"If the visualization you're using aggregates "
"points (e.g., box plot, histogram, etc.) you can "
"disregard this warning.")
warnings.warn(msg)
except TypeError:
pass
plot_options = _plot_option_logic(plot_options)
fig = tools._replace_newline(figure) # does not mutate figure
data = fig.get('data', [])
plot_options['layout'] = fig.get('layout', {})
response = v1.clientresp(data, **plot_options)
# Check if the url needs a secret key
url = response.json()['url']
if plot_options['sharing'] == 'secret':
if 'share_key=' not in url:
# add_share_key_to_url updates the url to include the share_key
url = add_share_key_to_url(url)
if plot_options['auto_open']:
_open_url(url)
return url
def iplot_mpl(fig, resize=True, strip_style=False, update=None,
**plot_options):
"""Replot a matplotlib figure with plotly in IPython.
This function:
1. converts the mpl figure into JSON (run help(plolty.tools.mpl_to_plotly))
2. makes a request to Plotly to save this figure in your account
3. displays the image in your IPython output cell
Positional agruments:
fig -- a figure object from matplotlib
Keyword arguments:
resize (default=True) -- allow plotly to choose the figure size
strip_style (default=False) -- allow plotly to choose style options
update (default=None) -- update the resulting figure with an 'update'
dictionary-like object resembling a plotly 'Figure' object
Additional keyword arguments:
plot_options -- run help(plotly.plotly.iplot)
"""
fig = tools.mpl_to_plotly(fig, resize=resize, strip_style=strip_style)
if update and isinstance(update, dict):
fig.update(update)
fig.validate()
elif update is not None:
raise exceptions.PlotlyGraphObjectError(
"'update' must be dictionary-like and a valid plotly Figure "
"object. Run 'help(plotly.graph_objs.Figure)' for more info."
)
return iplot(fig, **plot_options)
def plot_mpl(fig, resize=True, strip_style=False, update=None, **plot_options):
"""Replot a matplotlib figure with plotly.
This function:
1. converts the mpl figure into JSON (run help(plolty.tools.mpl_to_plotly))
2. makes a request to Plotly to save this figure in your account
3. opens your figure in a browser tab OR returns the unique figure url
Positional agruments:
fig -- a figure object from matplotlib
Keyword arguments:
resize (default=True) -- allow plotly to choose the figure size
strip_style (default=False) -- allow plotly to choose style options
update (default=None) -- update the resulting figure with an 'update'
dictionary-like object resembling a plotly 'Figure' object
Additional keyword arguments:
plot_options -- run help(plotly.plotly.plot)
"""
fig = tools.mpl_to_plotly(fig, resize=resize, strip_style=strip_style)
if update and isinstance(update, dict):
fig.update(update)
fig.validate()
elif update is not None:
raise exceptions.PlotlyGraphObjectError(
"'update' must be dictionary-like and a valid plotly Figure "
"object. Run 'help(plotly.graph_objs.Figure)' for more info."
)
return plot(fig, **plot_options)
def _swap_keys(obj, key1, key2):
"""Swap obj[key1] with obj[key2]"""
val1, val2 = None, None
try:
val2 = obj.pop(key1)
except KeyError:
pass
try:
val1 = obj.pop(key2)
except KeyError:
pass
if val2 is not None:
obj[key2] = val2
if val1 is not None:
obj[key1] = val1
def _swap_xy_data(data_obj):
"""Swap x and y data and references"""
swaps = [('x', 'y'),
('x0', 'y0'),
('dx', 'dy'),
('xbins', 'ybins'),
('nbinsx', 'nbinsy'),
('autobinx', 'autobiny'),
('error_x', 'error_y')]
for swap in swaps:
_swap_keys(data_obj, swap[0], swap[1])
try:
rows = len(data_obj['z'])
cols = len(data_obj['z'][0])
for row in data_obj['z']:
if len(row) != cols:
raise TypeError
# if we can't do transpose, we hit an exception before here
z = data_obj.pop('z')
data_obj['z'] = [[0 for rrr in range(rows)] for ccc in range(cols)]
for iii in range(rows):
for jjj in range(cols):
data_obj['z'][jjj][iii] = z[iii][jjj]
except (KeyError, TypeError, IndexError) as err:
warn = False
try:
if data_obj['z'] is not None:
warn = True
if len(data_obj['z']) == 0:
warn = False
except (KeyError, TypeError):
pass
if warn:
warnings.warn(
"Data in this file required an 'xy' swap but the 'z' matrix "
"in one of the data objects could not be transposed. Here's "
"why:\n\n{}".format(repr(err))
)
def get_figure(file_owner_or_url, file_id=None, raw=False):
"""Returns a JSON figure representation for the specified file
Plotly uniquely identifies figures with a 'file_owner'/'file_id' pair.
Since each file is given a corresponding unique url, you may also simply
pass a valid plotly url as the first argument.
Examples:
fig = get_figure('https://plot.ly/~chris/1638')
fig = get_figure('chris', 1638)
Note, if you're using a file_owner string as the first argument, you MUST
specify a `file_id` keyword argument. Else, if you're using a url string
as the first argument, you MUST NOT specify a `file_id` keyword argument,
or file_id must be set to Python's None value.
Positional arguments:
file_owner_or_url (string) -- a valid plotly username OR a valid plotly url
Keyword arguments:
file_id (default=None) -- an int or string that can be converted to int
if you're using a url, don't fill this in!
raw (default=False) -- if true, return unicode JSON string verbatim**
**by default, plotly will return a Figure object (run help(plotly
.graph_objs.Figure)). This representation decodes the keys and values from
unicode (if possible), removes information irrelevant to the figure
representation, and converts the JSON dictionary objects to plotly
`graph objects`.
"""
plotly_rest_url = get_config()['plotly_domain']
if file_id is None: # assume we're using a url
url = file_owner_or_url
if url[:len(plotly_rest_url)] != plotly_rest_url:
raise exceptions.PlotlyError(
"Because you didn't supply a 'file_id' in the call, "
"we're assuming you're trying to snag a figure from a url. "
"You supplied the url, '{0}', we expected it to start with "
"'{1}'."
"\nRun help on this function for more information."
"".format(url, plotly_rest_url))
head = plotly_rest_url + "/~"
file_owner = url.replace(head, "").split('/')[0]
file_id = url.replace(head, "").split('/')[1]
else:
file_owner = file_owner_or_url
try:
int(file_id)
except ValueError:
raise exceptions.PlotlyError(
"The 'file_id' argument was not able to be converted into an "
"integer number. Make sure that the positional 'file_id' argument "
"is a number that can be converted into an integer or a string "
"that can be converted into an integer."
)
if int(file_id) < 0:
raise exceptions.PlotlyError(
"The 'file_id' argument must be a non-negative number."
)
fid = '{}:{}'.format(file_owner, file_id)
response = v2.plots.content(fid, inline_data=True)
figure = response.json()
# Fix 'histogramx', 'histogramy', and 'bardir' stuff
for index, entry in enumerate(figure['data']):
try:
# Use xbins to bin data in x, and ybins to bin data in y
if all((entry['type'] == 'histogramy', 'xbins' in entry,
'ybins' not in entry)):
entry['ybins'] = entry.pop('xbins')
# Convert bardir to orientation, and put the data into the axes
# it's eventually going to be used with
if entry['type'] in ['histogramx', 'histogramy']:
entry['type'] = 'histogram'
if 'bardir' in entry:
entry['orientation'] = entry.pop('bardir')
if entry['type'] == 'bar':
if entry['orientation'] == 'h':
_swap_xy_data(entry)
if entry['type'] == 'histogram':
if ('x' in entry) and ('y' not in entry):
if entry['orientation'] == 'h':
_swap_xy_data(entry)
del entry['orientation']
if ('y' in entry) and ('x' not in entry):
if entry['orientation'] == 'v':
_swap_xy_data(entry)
del entry['orientation']
figure['data'][index] = entry
except KeyError:
pass
# Remove stream dictionary if found in a data trace
# (it has private tokens in there we need to hide!)
for index, entry in enumerate(figure['data']):
if 'stream' in entry:
del figure['data'][index]['stream']
if raw:
return figure
return tools.get_valid_graph_obj(figure, obj_type='Figure')
@utils.template_doc(**tools.get_config_file())
class Stream:
"""
Interface to Plotly's real-time graphing API.
Initialize a Stream object with a stream_id
found in {plotly_domain}/settings.
Real-time graphs are initialized with a call to `plot` that embeds
your unique `stream_id`s in each of the graph's traces. The `Stream`
interface plots data to these traces, as identified with the unique
stream_id, in real-time.
Every viewer of the graph sees the same data at the same time.
View examples and tutorials here:
https://plot.ly/python/streaming/
Stream example:
# Initialize a streaming graph
# by embedding stream_id's in the graph's traces
import plotly.plotly as py
from plotly.graph_objs import Data, Scatter, Stream
stream_id = "your_stream_id" # See {plotly_domain}/settings
py.plot(Data([Scatter(x=[], y=[],
stream=Stream(token=stream_id, maxpoints=100))]))
# Stream data to the import trace
stream = Stream(stream_id) # Initialize a stream object
stream.open() # Open the stream
stream.write(dict(x=1, y=1)) # Plot (1, 1) in your graph
"""
HTTP_PORT = 80
HTTPS_PORT = 443
@utils.template_doc(**tools.get_config_file())
def __init__(self, stream_id):
"""
Initialize a Stream object with your unique stream_id.
Find your stream_id at {plotly_domain}/settings.
For more help, see: `help(plotly.plotly.Stream)`
or see examples and tutorials here:
https://plot.ly/python/streaming/
"""
self.stream_id = stream_id
self._stream = None
def get_streaming_specs(self):
"""
Returns the streaming server, port, ssl_enabled flag, and headers.
"""
streaming_url = get_config()['plotly_streaming_domain']
ssl_verification_enabled = get_config()['plotly_ssl_verification']
ssl_enabled = 'https' in streaming_url
port = self.HTTPS_PORT if ssl_enabled else self.HTTP_PORT
# If no scheme (https/https) is included in the streaming_url, the
# host will be None. Use streaming_url in this case.
host = (six.moves.urllib.parse.urlparse(streaming_url).hostname or
streaming_url)
headers = {'Host': host, 'plotly-streamtoken': self.stream_id}
streaming_specs = {
'server': host,
'port': port,
'ssl_enabled': ssl_enabled,
'ssl_verification_enabled': ssl_verification_enabled,
'headers': headers
}
return streaming_specs
def heartbeat(self, reconnect_on=(200, '', 408)):
"""
Keep stream alive. Streams will close after ~1 min of inactivity.
If the interval between stream writes is > 30 seconds, you should
consider adding a heartbeat between your stream.write() calls like so:
>>> stream.heartbeat()
"""
try:
self._stream.write('\n', reconnect_on=reconnect_on)
except AttributeError:
raise exceptions.PlotlyError(
"Stream has not been opened yet, "
"cannot write to a closed connection. "
"Call `open()` on the stream to open the stream."
)
@property
def connected(self):
if self._stream is None:
return False
return self._stream._isconnected()
def open(self):
"""
Open streaming connection to plotly.
For more help, see: `help(plotly.plotly.Stream)`
or see examples and tutorials here:
https://plot.ly/python/streaming/
"""
streaming_specs = self.get_streaming_specs()
self._stream = chunked_requests.Stream(**streaming_specs)
def write(self, trace, layout=None, validate=True,
reconnect_on=(200, '', 408)):
"""
Write to an open stream.
Once you've instantiated a 'Stream' object with a 'stream_id',
you can 'write' to it in real time.
positional arguments:
trace - A valid plotly trace object (e.g., Scatter, Heatmap, etc.).
Not all keys in these are `stremable` run help(Obj) on the type
of trace your trying to stream, for each valid key, if the key
is streamable, it will say 'streamable = True'. Trace objects
must be dictionary-like.
keyword arguments:
layout (default=None) - A valid Layout object
Run help(plotly.graph_objs.Layout)
validate (default = True) - Validate this stream before sending?
This will catch local errors if set to
True.
Some valid keys for trace dictionaries:
'x', 'y', 'text', 'z', 'marker', 'line'
Examples:
>>> write(dict(x=1, y=2)) # assumes 'scatter' type
>>> write(Bar(x=[1, 2, 3], y=[10, 20, 30]))
>>> write(Scatter(x=1, y=2, text='scatter text'))
>>> write(Scatter(x=1, y=3, marker=Marker(color='blue')))
>>> write(Heatmap(z=[[1, 2, 3], [4, 5, 6]]))
The connection to plotly's servers is checked before writing
and reconnected if disconnected and if the response status code
is in `reconnect_on`.
For more help, see: `help(plotly.plotly.Stream)`
or see examples and tutorials here:
http://nbviewer.ipython.org/github/plotly/python-user-guide/blob/master/s7_streaming/s7_streaming.ipynb
"""
stream_object = dict()
stream_object.update(trace)
if 'type' not in stream_object:
stream_object['type'] = 'scatter'
if validate:
try:
tools.validate(stream_object, stream_object['type'])
except exceptions.PlotlyError as err:
raise exceptions.PlotlyError(
"Part of the data object with type, '{0}', is invalid. "
"This will default to 'scatter' if you do not supply a "
"'type'. If you do not want to validate your data objects "
"when streaming, you can set 'validate=False' in the call "
"to 'your_stream.write()'. Here's why the object is "
"invalid:\n\n{1}".format(stream_object['type'], err)
)
if layout is not None:
try:
tools.validate(layout, 'Layout')
except exceptions.PlotlyError as err:
raise exceptions.PlotlyError(
"Your layout kwarg was invalid. "
"Here's why:\n\n{0}".format(err)
)
del stream_object['type']
if layout is not None:
stream_object.update(dict(layout=layout))
# TODO: allow string version of this?
jdata = _json.dumps(stream_object, cls=utils.PlotlyJSONEncoder)
jdata += "\n"
try:
self._stream.write(jdata, reconnect_on=reconnect_on)
except AttributeError:
raise exceptions.PlotlyError(
"Stream has not been opened yet, "
"cannot write to a closed connection. "
"Call `open()` on the stream to open the stream.")
def close(self):
"""
Close the stream connection to plotly's streaming servers.
For more help, see: `help(plotly.plotly.Stream)`
or see examples and tutorials here:
https://plot.ly/python/streaming/
"""
try:
self._stream.close()
except AttributeError:
raise exceptions.PlotlyError("Stream has not been opened yet.")
class image:
"""
Helper functions wrapped around plotly's static image generation api.
"""
@staticmethod
def get(figure_or_data, format='png', width=None, height=None, scale=None):
"""Return a static image of the plot described by `figure_or_data`.
positional arguments:
- figure_or_data: The figure dict-like or data list-like object that
describes a plotly figure.
Same argument used in `py.plot`, `py.iplot`,
see https://plot.ly/python for examples
- format: 'png', 'svg', 'jpeg', 'pdf'
- width: output width
- height: output height
- scale: Increase the resolution of the image by `scale`
amount (e.g. `3`)
Only valid for PNG and JPEG images.
example:
```
import plotly.plotly as py
fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
py.image.get(fig, 'png', scale=3)
```
"""
# TODO: format is a built-in name... we shouldn't really use it
if isinstance(figure_or_data, dict):
figure = figure_or_data
elif isinstance(figure_or_data, list):
figure = {'data': figure_or_data}
else:
raise exceptions.PlotlyEmptyDataError(
"`figure_or_data` must be a dict or a list."
)
if format not in ['png', 'svg', 'jpeg', 'pdf']:
raise exceptions.PlotlyError(
"Invalid format. This version of your Plotly-Python "
"package currently only supports png, svg, jpeg, and pdf. "
"Learn more about image exporting, and the currently "
"supported file types here: "
"https://plot.ly/python/static-image-export/"
)
if scale is not None:
try:
scale = float(scale)
except:
raise exceptions.PlotlyError(
"Invalid scale parameter. Scale must be a number."
)
payload = {'figure': figure, 'format': format}
if width is not None:
payload['width'] = width
if height is not None:
payload['height'] = height
if scale is not None:
payload['scale'] = scale
response = v2.images.create(payload)
headers = response.headers
if ('content-type' in headers and
headers['content-type'] in ['image/png', 'image/jpeg',
'application/pdf',
'image/svg+xml']):
return response.content
elif ('content-type' in headers and
'json' in headers['content-type']):
return response.json()['image']
@classmethod
def ishow(cls, figure_or_data, format='png', width=None, height=None,
scale=None):
"""Display a static image of the plot described by `figure_or_data`
in an IPython Notebook.
positional arguments:
- figure_or_data: The figure dict-like or data list-like object that
describes a plotly figure.
Same argument used in `py.plot`, `py.iplot`,
see https://plot.ly/python for examples
- format: 'png', 'svg', 'jpeg', 'pdf'
- width: output width
- height: output height
- scale: Increase the resolution of the image by `scale` amount
Only valid for PNG and JPEG images.
example:
```
import plotly.plotly as py
fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
py.image.ishow(fig, 'png', scale=3)
"""
if format == 'pdf':
raise exceptions.PlotlyError(
"Aw, snap! "
"It's not currently possible to embed a pdf into "
"an IPython notebook. You can save the pdf "
"with the `image.save_as` or you can "
"embed an png, jpeg, or svg.")
img = cls.get(figure_or_data, format, width, height, scale)
from IPython.display import display, Image, SVG
if format == 'svg':
display(SVG(img))
else:
display(Image(img))
@classmethod
def save_as(cls, figure_or_data, filename, format=None, width=None,
height=None, scale=None):
"""Save a image of the plot described by `figure_or_data` locally as
`filename`.
Valid image formats are 'png', 'svg', 'jpeg', and 'pdf'.
The format is taken as the extension of the filename or as the
supplied format.
positional arguments:
- figure_or_data: The figure dict-like or data list-like object that
describes a plotly figure.
Same argument used in `py.plot`, `py.iplot`,
see https://plot.ly/python for examples
- filename: The filepath to save the image to
- format: 'png', 'svg', 'jpeg', 'pdf'
- width: output width
- height: output height
- scale: Increase the resolution of the image by `scale` amount
Only valid for PNG and JPEG images.
example:
```
import plotly.plotly as py
fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
py.image.save_as(fig, 'my_image.png', scale=3)
```
"""
# todo: format shadows built-in name
(base, ext) = os.path.splitext(filename)
if not ext and not format:
filename += '.png'
elif ext and not format:
format = ext[1:]
elif not ext and format:
filename += '.' + format
img = cls.get(figure_or_data, format, width, height, scale)
f = open(filename, 'wb')
f.write(img)
f.close()
class file_ops:
"""
Interface to Plotly's File System API
"""
@classmethod
def mkdirs(cls, folder_path):
"""
Create folder(s) specified by folder_path in your Plotly account.
If the intermediate directories do not exist,
they will be created. If they already exist,
no error will be thrown.
Mimics the shell's mkdir -p.
Returns:
- 200 if folders already existed, nothing was created
- 201 if path was created
Raises:
- exceptions.PlotlyRequestError with status code
400 if the path already exists.
Usage:
>> mkdirs('new folder')
>> mkdirs('existing folder/new folder')
>> mkdirs('new/folder/path')
"""
response = v2.folders.create({'path': folder_path})
return response.status_code
class grid_ops:
"""
Interface to Plotly's Grid API.
Plotly Grids are Plotly's tabular data object, rendered
in an online spreadsheet. Plotly graphs can be made from
references of columns of Plotly grid objects. Free-form
JSON Metadata can be saved with Plotly grids.
To create a Plotly grid in your Plotly account from Python,
see `grid_ops.upload`.
To add rows or columns to an existing Plotly grid, see
`grid_ops.append_rows` and `grid_ops.append_columns`
respectively.
To delete one of your grid objects, see `grid_ops.delete`.
"""
@classmethod
def _fill_in_response_column_ids(cls, request_columns,
response_columns, grid_id):
for req_col in request_columns:
for resp_col in response_columns:
if resp_col['name'] == req_col.name:
req_col.id = '{0}:{1}'.format(grid_id, resp_col['uid'])
response_columns.remove(resp_col)
@staticmethod
def ensure_uploaded(fid):
if fid:
return
raise exceptions.PlotlyError(
'This operation requires that the grid has already been uploaded '
'to Plotly. Try `uploading` first.'
)
@classmethod
def upload(cls, grid, filename,
world_readable=True, auto_open=True, meta=None):
"""
Upload a grid to your Plotly account with the specified filename.
Positional arguments:
- grid: A plotly.grid_objs.Grid object,
call `help(plotly.grid_ops.Grid)` for more info.
- filename: Name of the grid to be saved in your Plotly account.
To save a grid in a folder in your Plotly account,
separate specify a filename with folders and filename
separated by backslashes (`/`).
If a grid, plot, or folder already exists with the same
filename, a `plotly.exceptions.RequestError` will be
thrown with status_code 409
Optional keyword arguments:
- world_readable (default=True): make this grid publically (True)
or privately (False) viewable.
- auto_open (default=True): Automatically open this grid in
the browser (True)
- meta (default=None): Optional Metadata to associate with
this grid.
Metadata is any arbitrary
JSON-encodable object, for example:
`{"experiment name": "GaAs"}`
Filenames must be unique. To overwrite a grid with the same filename,
you'll first have to delete the grid with the blocking name. See
`plotly.plotly.grid_ops.delete`.
Usage example 1: Upload a plotly grid
```
from plotly.grid_objs import Grid, Column
import plotly.plotly as py
column_1 = Column([1, 2, 3], 'time')
column_2 = Column([4, 2, 5], 'voltage')
grid = Grid([column_1, column_2])
py.grid_ops.upload(grid, 'time vs voltage')
```
Usage example 2: Make a graph based with data that is sourced
from a newly uploaded Plotly grid
```
import plotly.plotly as py
from plotly.grid_objs import Grid, Column
from plotly.graph_objs import Scatter
# Upload a grid
column_1 = Column([1, 2, 3], 'time')
column_2 = Column([4, 2, 5], 'voltage')
grid = Grid([column_1, column_2])
py.grid_ops.upload(grid, 'time vs voltage')
# Build a Plotly graph object sourced from the
# grid's columns
trace = Scatter(xsrc=grid[0], ysrc=grid[1])
py.plot([trace], filename='graph from grid')
```
"""
# Make a folder path
if filename[-1] == '/':
filename = filename[0:-1]
paths = filename.split('/')
parent_path = '/'.join(paths[0:-1])
filename = paths[-1]
if parent_path != '':
file_ops.mkdirs(parent_path)
# transmorgify grid object into plotly's format
grid_json = grid._to_plotly_grid_json()
if meta is not None:
grid_json['metadata'] = meta
payload = {
'filename': filename,
'data': grid_json,
'world_readable': world_readable
}
if parent_path != '':
payload['parent_path'] = parent_path