13
13
import os .path
14
14
import warnings
15
15
import six
16
+ import requests
16
17
17
18
from plotly import utils
18
19
from plotly import exceptions
@@ -30,6 +31,12 @@ def warning_on_one_line(message, category, filename, lineno, file=None, line=Non
30
31
except ImportError :
31
32
_matplotlylib_imported = False
32
33
34
+ try :
35
+ import IPython
36
+ _ipython_imported = True
37
+ except ImportError :
38
+ _ipython_imported = False
39
+
33
40
PLOTLY_DIR = os .path .join (os .path .expanduser ("~" ), ".plotly" )
34
41
CREDENTIALS_FILE = os .path .join (PLOTLY_DIR , ".credentials" )
35
42
CONFIG_FILE = os .path .join (PLOTLY_DIR , ".config" )
@@ -283,11 +290,21 @@ def embed(file_owner_or_url, file_id=None, width="100%", height=525):
283
290
return html (s , hide = False )
284
291
except :
285
292
pass
286
- try :
287
- from IPython .display import HTML , display
288
- display (HTML (s ))
289
- except :
290
- pass
293
+ if _ipython_imported :
294
+ if file_id :
295
+ url = "{plotly_domain}/~{un}/{fid}" .format (
296
+ plotly_domain = get_config_file ()['plotly_domain' ],
297
+ un = file_owner_or_url ,
298
+ fid = file_id )
299
+ else :
300
+ url = file_owner_or_url
301
+ return PlotlyDisplay (url )
302
+ else :
303
+ warnings .warn (
304
+ "Looks like you're not using IPython or Sage to embed this plot. "
305
+ "If you just want the *embed code*, try using `get_embed()` "
306
+ "instead."
307
+
291
308
292
309
293
310
### mpl-related tools ###
@@ -532,3 +549,40 @@ def _replace_newline(obj):
532
549
return s
533
550
else :
534
551
return obj # we return the actual reference... but DON'T mutate.
552
+
553
+
554
+ if _ipython_imported :
555
+ class PlotlyDisplay (IPython .core .display .HTML ):
556
+ """An IPython display object for use with plotly urls
557
+
558
+ PlotlyDisplay objects should be instantiated with a url for a plot.
559
+ IPython will *choose* the proper display representation from any
560
+ Python object, and using provided methods if they exist. By defining
561
+ the following, if an HTML display is unusable, the PlotlyDisplay
562
+ object can provide alternate representations.
563
+
564
+ """
565
+ def __init__ (self , url ):
566
+ self .resource = url
567
+ self .embed_code = get_embed (url )
568
+ super (PlotlyDisplay , self ).__init__ (data = self .embed_code )
569
+
570
+ def _repr_svg_ (self ):
571
+ url = self .resource + ".svg"
572
+ res = requests .get (url )
573
+ return res .content
574
+
575
+ def _repr_png_ (self ):
576
+ url = self .resource + ".png"
577
+ res = requests .get (url )
578
+ return res .content
579
+
580
+ def _repr_pdf_ (self ):
581
+ url = self .resource + ".pdf"
582
+ res = requests .get (url )
583
+ return res .content
584
+
585
+ def _repr_jpeg_ (self ):
586
+ url = self .resource + ".jpeg"
587
+ res = requests .get (url )
588
+ return res .content
0 commit comments