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
223 lines (200 loc) · 6.44 KB
/
plotly.py
File metadata and controls
223 lines (200 loc) · 6.44 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
import requests
import json
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 = json.loads(r.text)
if 'error' in r.keys():
if not r['error'] == '':
print(r['error'])
if 'warning' in r.keys():
print(r['warning'])
if 'message' in r.keys():
print(r['message'])
return r
class plotly:
def __init__(self, username=None, key=None,verbose=True):
''' plotly constructor. Supply username and api key.
'''
self.un = username
self.key = key
self.__filename = None
self.__fileopt = None
self.verbose = verbose
self.open = False
def iplot(self, *args, **kwargs):
''' for use in ipython notebooks '''
res = self.__callplot(*args, **kwargs)
width = kwargs.get('width', 600)
height = kwargs.get('height', 600)
s = '<iframe height="%s" id="igraph" scrolling="no" seamless="seamless" src="%s" width="%s"></iframe>' %\
(height+50, "/".join(map(str, [res['url'], width, height])), width+50)
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
def plot(self, *args, **kwargs):
res = self.__callplot(*args, **kwargs)
if res['error'] == '' and self.open:
from webbrowser import open as wbopen
wbopen(res['url'])
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, ...], **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.keys() else self.un
key = kwargs['key'] 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 = '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
import datetime
try:
if isinstance(obj,(datetime.datetime, datetime.date)):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj[0],(datetime.datetime, datetime.date)):
return [o.strftime('%Y-%m-%d %H:%M:%S') 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 = json.loads(r.text)
if 'error' in r.keys():
print(r['error'])
if 'warning' in r.keys():
print(r['warning'])
if 'message' in r.keys():
if self.verbose:
print(r['message'])
if 'filename' in r.keys():
self.__filename = r['filename']
return r