Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9fe9444

Browse files
committed
improved json encoding + open argument
- datetime, better numpy, and prelim pandas json encoding supported - py.open = True will open the returned url of the plot
1 parent 65ebbe6 commit 9fe9444

File tree

2 files changed

+79
-17
lines changed

2 files changed

+79
-17
lines changed

plotly/plotly.py

Lines changed: 56 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def signup(un, email):
1212
:un: <string> username
1313
:email: <string> email address
1414
'''
15-
payload = {'version': '0.4', 'un': un, 'email': email, 'platform':'Python'}
15+
payload = {'version': '0.5.2', 'un': un, 'email': email, 'platform':'Python'}
1616
r = requests.post('https://plot.ly/apimkacct', data=payload)
1717
r = json.loads(r.text)
1818
if 'error' in r.keys():
@@ -34,10 +34,11 @@ def __init__(self, username=None, key=None,verbose=True):
3434
self.__filename = None
3535
self.__fileopt = None
3636
self.verbose = verbose
37+
self.open = False
3738

3839
def iplot(self, *args, **kwargs):
3940
''' for use in ipython notebooks '''
40-
res = self.plot(*args, **kwargs)
41+
res = self.__callplot(*args, **kwargs)
4142
width = kwargs.get('width', 600)
4243
height = kwargs.get('height', 600)
4344
s = '<iframe height="'+str(height+50)+'" id="igraph" scrolling="no" seamless="seamless" src="'+res['url']+'/'+str(width)+'/'+str(height)+'" width="'+str(width+50)+'"></iframe>'
@@ -48,6 +49,13 @@ def iplot(self, *args, **kwargs):
4849
return s
4950

5051
def plot(self, *args, **kwargs):
52+
res = self.__callplot(*args, **kwargs)
53+
if res['error'] == '' and self.open:
54+
from webbrowser import open as wbopen
55+
wbopen(res['url'])
56+
return res
57+
58+
def __callplot(self, *args, **kwargs):
5159
''' Make a plot in plotly.
5260
Two interfaces:
5361
1 - ploty.plot(x1, y1[,x2,y2,...],**kwargs)
@@ -131,27 +139,58 @@ def style(self, *args, **kwargs):
131139
r = self.__makecall(args, un, key, origin, kwargs)
132140
return r
133141

142+
class __plotlyJSONEncoder(json.JSONEncoder):
143+
def numpyJSONEncoder(self, obj):
144+
try:
145+
import numpy
146+
if type(obj).__module__ == numpy.__name__:
147+
l = obj.tolist()
148+
d = self.datetimeJSONEncoder(l)
149+
return d if d else l
150+
except:
151+
pass
152+
return None
153+
def datetimeJSONEncoder(self, obj):
154+
# if datetime or iterable of datetimes, convert to a string that plotly understands
155+
import datetime
156+
try:
157+
if isinstance(obj,(datetime.datetime, datetime.date)):
158+
return obj.strftime('%Y-%m-%d %H:%M:%S')
159+
elif isinstance(obj[0],(datetime.datetime, datetime.date)):
160+
return [o.strftime('%Y-%m-%d %H:%M:%S') for o in obj]
161+
except:
162+
pass
163+
return None
164+
def pandasJSONEncoder(self, obj):
165+
try:
166+
import pandas
167+
if isinstance(obj, pandas.DataFrame):
168+
return obj.to_json()
169+
except:
170+
pass
171+
return None
172+
def default(self, obj):
173+
try:
174+
return json.dumps(obj)
175+
except TypeError as e:
176+
encoders = (self.datetimeJSONEncoder, self.numpyJSONEncoder, self.pandasJSONEncoder)
177+
for encoder in encoders:
178+
s = encoder(obj)
179+
if s:
180+
return s
181+
raise e
182+
return json.JSONEncoder.default(self,obj)
183+
134184
def __makecall(self, args, un, key, origin, kwargs):
135-
version = '0.5'
185+
version = '0.5.2'
136186
platform = 'Python'
137-
138-
class NumpyAwareJSONEncoder(json.JSONEncoder):
139-
def default(self, obj):
140-
try:
141-
import numpy
142-
if isinstance(obj, numpy.ndarray) and obj.ndim == 1:
143-
return [x for x in obj]
144-
return json.JSONEncoder.default(self, obj)
145-
except:
146-
return json.JSONEncoder.default(self, obj)
147-
148-
args = json.dumps(args, cls=NumpyAwareJSONEncoder)
149-
kwargs = json.dumps(kwargs, cls=NumpyAwareJSONEncoder)
187+
188+
args = json.dumps(args, cls=self.__plotlyJSONEncoder)
189+
kwargs = json.dumps(kwargs, cls=self.__plotlyJSONEncoder)
150190
url = 'https://plot.ly/clientresp'
151191
payload = {'platform': platform, 'version': version, 'args': args, 'un': un, 'key': key, 'origin': origin, 'kwargs': kwargs}
152192
r = requests.post(url, data=payload)
153193
r = json.loads(r.text)
154-
155194
if 'error' in r.keys():
156195
print(r['error'])
157196
if 'warning' in r.keys():

setup.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from setuptools import setup
2+
3+
def readme():
4+
with open('README.txt') as f:
5+
return f.read()
6+
7+
setup(name='plotly',
8+
version='0.5.1',
9+
description='',
10+
url='https://plot.ly/api/python',
11+
author='Chris P',
12+
author_email='[email protected]',
13+
classifiers=['Development Status :: 3 - Alpha',
14+
'Programming Language :: Python :: 2.7',
15+
'Programming Language :: Python :: 3.3',
16+
'Topic :: Scientific/Engineering :: Visualization',
17+
],
18+
license='MIT',
19+
packages=['plotly'],
20+
install_requires=[
21+
'requests'
22+
],
23+
zip_safe=False)

0 commit comments

Comments
 (0)