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
303 lines (273 loc) · 9.16 KB
/
plotly.py
File metadata and controls
303 lines (273 loc) · 9.16 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
import requests
import json
import warnings
import httplib
from .version import __version__
def signup(un, email):
''' Remote signup to plot.ly and plot.ly API
Returns:
:param r with r['tmp_pw']: Temporary password to access your plot.ly acount
:param r['api_key']: A key to use the API with
Full docs and examples at https://plot.ly/API
:un: <string> username
:email: <string> email address
'''
payload = {'version': __version__, 'un': un, 'email': email, 'platform':'Python'}
r = requests.post('https://plot.ly/apimkacct', data=payload)
r.raise_for_status()
r = json.loads(r.text)
if 'error' in r and r['error'] != '':
print(r['error'])
if 'warning' in r and r['warning'] != '':
warnings.warn(r['warning'])
if 'message' in r and r['message'] != '':
print(r['message'])
return r
def embed(url, width="100%", height=525):
return display(url, width, height, notebook=False)
def display(url, width="100%", height=525, notebook=True):
if isinstance( width, ( int, long ) ):
s = '<iframe height="%s" id="igraph" scrolling="no" seamless="seamless" src="%s" width="%s"></iframe>' %\
(height+25, "/".join(map(str,[url, width, height])), width+25)
else:
s = '<iframe height="%s" id="igraph" scrolling="no" seamless="seamless" src="%s" width="%s"></iframe>' %\
(height+25, url, width)
if not notebook:
return s
try:
# see, if we are in the SageMath Cloud
from sage_salvus import html
return html(s, hide=False)
except:
pass
try:
from IPython.display import HTML
return HTML(s)
except:
return s
class plotly:
def __init__(self, username_or_email=None, key=None,verbose=True):
''' plotly constructor. Supply username or email and api key.
'''
self.un = username_or_email
self.key = key
self.__filename = None
self.__fileopt = None
self.verbose = verbose
self.open = True
self.width = '100%'
self.height = 525
def ion(self):
self.open = True
def ioff(self):
self.open = False
def iplot(self, *args, **kwargs):
''' for use in ipython notebooks '''
res = self.__callplot(*args, **kwargs)
width = kwargs.get('width', self.width)
height = kwargs.get('height', self.height)
return display(res['url'], width, height)
def plot(self, *args, **kwargs):
res = self.__callplot(*args, **kwargs)
if 'error' in res and res['error'] == '' and self.open:
try:
from webbrowser import open as wbopen
wbopen(res['url'])
except:
pass
return res
def __callplot(self, *args, **kwargs):
''' Make a plot in plotly.
Two interfaces:
1 - ploty.plot(x1, y1[,x2,y2,...],**kwargs)
where x1, y1, .... are lists, numpy arrays
2 - plot.plot([data1[, data2, ...], **kwargs)
where data1 is a dict that is at least
{'x': x1, 'y': y1} but can contain more styling and sharing options.
kwargs accepts:
filename
fileopt
style
layout
See https://plot.ly/API for details.
Returns:
:param r with r['url']: A URL that displays the generated plot
:param r['filename']: The filename of the plot in your plotly account.
'''
un = kwargs['un'] if 'un' in kwargs else self.un
key = kwargs['key'] if 'key' in kwargs else self.key
if not un or not key:
raise Exception('Not Signed in')
if not 'filename' in kwargs:
kwargs['filename'] = self.__filename
if not 'fileopt' in kwargs:
kwargs['fileopt'] = self.__fileopt
origin = 'plot'
r = self.__makecall(args, un, key, origin, kwargs)
return r
def layout(self, *args, **kwargs):
''' Style the layout of a Plotly plot.
ploty.layout(layout,**kwargs)
:param layout - a dict that customizes the style of the layout,
the axes, and the legend.
:param kwargs - accepts:
filename
See https://plot.ly/API for details.
Returns:
:param r with r['url']: A URL that displays the generated plot
:param r['filename']: The filename of the plot in your plotly account.
'''
un = kwargs['un'] if 'un' in kwargs.keys() else self.un
key = kwargs['un'] if 'key' in kwargs.keys() else self.key
if not un or not key:
raise Exception('Not Signed in')
if not 'filename' in kwargs.keys():
kwargs['filename'] = self.__filename
if not 'fileopt' in kwargs.keys():
kwargs['fileopt'] = self.__fileopt
origin = 'layout'
r = self.__makecall(args, un, key, origin, kwargs)
return r
def style(self, *args, **kwargs):
''' Style the data traces of a Plotly plot.
ploty.style([data1,[,data2,...],**kwargs)
:param data1 - a dict that customizes the style of the i'th trace
:param kwargs - accepts:
filename
See https://plot.ly/API for details.
Returns:
:param r with r['url']: A URL that displays the generated plot
:param r['filename']: The filename of the plot in your plotly account.
'''
un = kwargs['un'] if 'un' in kwargs.keys() else self.un
key = kwargs['un'] if 'key' in kwargs.keys() else self.key
if not un or not key:
raise Exception('Not Signed in')
if not 'filename' in kwargs.keys():
kwargs['filename'] = self.__filename
if not 'fileopt' in kwargs.keys():
kwargs['fileopt'] = self.__fileopt
origin = 'style'
r = self.__makecall(args, un, key, origin, kwargs)
return r
class __plotlyJSONEncoder(json.JSONEncoder):
def numpyJSONEncoder(self, obj):
try:
import numpy
if type(obj).__module__.split('.')[0] == numpy.__name__:
l = obj.tolist()
d = self.datetimeJSONEncoder(l)
return d if d is not None else l
except:
pass
return None
def datetimeJSONEncoder(self, obj):
# if datetime or iterable of datetimes, convert to a string that plotly understands
# format as %Y-%m-%d %H:%M:%S.%f, %Y-%m-%d %H:%M:%S, or %Y-%m-%d depending on what non-zero resolution was provided
import datetime
try:
if isinstance(obj,(datetime.datetime, datetime.date)):
if obj.microsecond != 0:
return obj.strftime('%Y-%m-%d %H:%M:%S.%f')
elif obj.second != 0 or obj.minute != 0 or obj.hour != 0:
return obj.strftime('%Y-%m-%d %H:%M:%S')
else:
return obj.strftime('%Y-%m-%d')
elif isinstance(obj[0],(datetime.datetime, datetime.date)):
return [o.strftime('%Y-%m-%d %H:%M:%S.%f') if o.microsecond != 0 else
o.strftime('%Y-%m-%d %H:%M:%S') if o.second != 0 or o.minute != 0 or o.hour != 0 else
o.strftime('%Y-%m-%d')
for o in obj]
except:
pass
return None
def pandasJSONEncoder(self, obj):
try:
import pandas
if isinstance(obj, pandas.Series):
return obj.tolist()
except:
pass
return None
def sageJSONEncoder(self, obj):
try:
from sage.all import RR, ZZ
if obj in RR:
return float(obj)
elif obj in ZZ:
return int(obj)
except:
pass
return None
def default(self, obj):
try:
return json.dumps(obj)
except TypeError as e:
encoders = (self.datetimeJSONEncoder, self.numpyJSONEncoder, self.pandasJSONEncoder, self.sageJSONEncoder)
for encoder in encoders:
s = encoder(obj)
if s is not None:
return s
raise e
return json.JSONEncoder.default(self,obj)
def __makecall(self, args, un, key, origin, kwargs):
platform = 'Python'
args = json.dumps(args, cls=self.__plotlyJSONEncoder)
kwargs = json.dumps(kwargs, cls=self.__plotlyJSONEncoder)
url = 'https://plot.ly/clientresp'
payload = {'platform': platform, 'version': __version__, 'args': args, 'un': un, 'key': key, 'origin': origin, 'kwargs': kwargs}
r = requests.post(url, data=payload)
r.raise_for_status()
r = json.loads(r.text)
if 'error' in r and r['error'] != '':
print(r['error'])
if 'warning' in r and r['warning'] != '':
warnings.warn(r['warning'])
if 'message' in r and r['message'] != '' and self.verbose:
print(r['message'])
return r
class stream:
def __init__(self, token):
''' plotly stream constructor
token found at https://plot.ly/settings
'''
self.token = token
self.connected = False
def init(self):
''' Initialize a streaming connection to plotly
'''
self.conn = httplib.HTTPConnection('stream.plot.ly', 80)
self.conn.putrequest('POST', '/')
self.conn.putheader('Host', 'stream.plot.ly')
self.conn.putheader('User-Agent', 'Python-Plotly')
self.conn.putheader('Transfer-Encoding', 'chunked')
self.conn.putheader('Connection', 'close')
self.conn.putheader('plotly-streamtoken', self.token)
self.conn.endheaders()
self.connected=True
def write(self, data):
''' Write data to plotly's streaming servers
data is a plotly formatted data dict
with data keys 'x', 'y', 'text', 'z', 'marker', 'line'
'x', 'y', 'text', and 'z' can have values of strings, numbers, or lists
'marker', and 'line' have dicts as values with keys 'size', 'color', 'symbol'
Examples:
{'x': 1, 'y': 2}
{'x': [1, 2, 3], 'y': [10, 20, 30]}
{'x': 1, 'y': 3, 'text': 'hover text'}
{'x': 1, 'y': 3, 'marker': {'color': 'blue'}}
{'z': [[1,2,3], [4,5,6]]}
'''
if not self.connected:
self.init()
# plotly's streaming API takes new-line separated json objects
msg = json.dumps(data)+'\n'
msglen = format(len(msg), 'x')
# chunked encoding requests contain the messege length in hex, \r\n, and then the message
self.conn.send('{msglen}\r\n{msg}\r\n'.format(msglen=msglen, msg=msg))
def close(self):
''' Close connection to plotly's streaming servers
'''
self.conn.send('0\r\n\r\n')
self.conn.close()
self.connected=False