|
| 1 | +""" Plotly Offline |
| 2 | + A module to use Plotly's graphing library with Python |
| 3 | + without connecting to a public or private plotly enterprise |
| 4 | + server. |
| 5 | +""" |
| 6 | +from __future__ import absolute_import |
| 7 | + |
| 8 | +import uuid |
| 9 | +import json |
| 10 | +import os |
| 11 | +import requests |
| 12 | + |
| 13 | +from plotly import utils |
| 14 | +from plotly import tools |
| 15 | +from plotly.exceptions import PlotlyError |
| 16 | +from plotly import session |
| 17 | + |
| 18 | +PLOTLY_OFFLINE_DIRECTORY = plotlyjs_path = os.path.expanduser( |
| 19 | + os.path.join(*'~/.plotly/plotlyjs'.split('/'))) |
| 20 | +PLOTLY_OFFLINE_BUNDLE = os.path.join(PLOTLY_OFFLINE_DIRECTORY, |
| 21 | + 'plotly-ipython-offline-bundle.js') |
| 22 | + |
| 23 | + |
| 24 | +__PLOTLY_OFFLINE_INITIALIZED = False |
| 25 | + |
| 26 | + |
| 27 | +def download_plotlyjs(download_url): |
| 28 | + if not os.path.exists(PLOTLY_OFFLINE_DIRECTORY): |
| 29 | + os.makedirs(PLOTLY_OFFLINE_DIRECTORY) |
| 30 | + |
| 31 | + res = requests.get(download_url) |
| 32 | + res.raise_for_status() |
| 33 | + |
| 34 | + with open(PLOTLY_OFFLINE_BUNDLE, 'wb') as f: |
| 35 | + f.write(res.content) |
| 36 | + |
| 37 | + print('\n'.join([ |
| 38 | + 'Success! Now start an IPython notebook and run the following ' + |
| 39 | + 'code to make your first offline graph:', |
| 40 | + '', |
| 41 | + 'import plotly', |
| 42 | + 'plotly.offline.init_notebook_mode() ' |
| 43 | + '# run at the start of every ipython notebook', |
| 44 | + 'plotly.offline.iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}])' |
| 45 | + ])) |
| 46 | + |
| 47 | + |
| 48 | +def init_notebook_mode(): |
| 49 | + """ |
| 50 | + Initialize Plotly Offline mode in an IPython Notebook. |
| 51 | + Run this function at the start of an IPython notebook |
| 52 | + to load the necessary javascript files for creating |
| 53 | + Plotly graphs with plotly.offline.iplot. |
| 54 | + """ |
| 55 | + if not tools._ipython_imported: |
| 56 | + raise ImportError('`iplot` can only run inside an IPython Notebook.') |
| 57 | + from IPython.display import HTML, display |
| 58 | + |
| 59 | + if not os.path.exists(PLOTLY_OFFLINE_BUNDLE): |
| 60 | + raise PlotlyError('Plotly Offline source file at {source_path} ' |
| 61 | + 'is not found.\n' |
| 62 | + 'If you have a Plotly Offline license, then try ' |
| 63 | + 'running plotly.offline.download_plotlyjs(url) ' |
| 64 | + 'with a licensed download url.\n' |
| 65 | + "Don't have a Plotly Offline license? " |
| 66 | + 'Contact [email protected] learn more about licensing.\n' |
| 67 | + |
| 68 | + .format(source_path=PLOTLY_OFFLINE_BUNDLE)) |
| 69 | + |
| 70 | + global __PLOTLY_OFFLINE_INITIALIZED |
| 71 | + __PLOTLY_OFFLINE_INITIALIZED = True |
| 72 | + display(HTML('<script type="text/javascript">' + |
| 73 | + open(PLOTLY_OFFLINE_BUNDLE).read() + '</script>')) |
| 74 | + |
| 75 | + |
| 76 | +def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly'): |
| 77 | + """ |
| 78 | + Draw plotly graphs inside an IPython notebook without |
| 79 | + connecting to an external server. |
| 80 | + To save the chart to Plotly Cloud or Plotly Enterprise, use |
| 81 | + `plotly.plotly.iplot`. |
| 82 | + To embed an image of the chart, use `plotly.image.ishow`. |
| 83 | +
|
| 84 | + figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or |
| 85 | + dict or list that describes a Plotly graph. |
| 86 | + See https://plot.ly/python/ for examples of |
| 87 | + graph descriptions. |
| 88 | +
|
| 89 | + Keyword arguments: |
| 90 | + show_link (default=True) -- display a link in the bottom-right corner of |
| 91 | + of the chart that will export the chart to |
| 92 | + Plotly Cloud or Plotly Enterprise |
| 93 | + link_text (default='Export to plot.ly') -- the text of export link |
| 94 | +
|
| 95 | + Example: |
| 96 | + ``` |
| 97 | + from plotly.offline import init_notebook_mode, iplot |
| 98 | + init_notebook_mode() |
| 99 | +
|
| 100 | + iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) |
| 101 | + ``` |
| 102 | + """ |
| 103 | + if not __PLOTLY_OFFLINE_INITIALIZED: |
| 104 | + raise PlotlyError('\n'.join([ |
| 105 | + 'Plotly Offline mode has not been initialized in this notebook. ' |
| 106 | + 'Run: ', |
| 107 | + '', |
| 108 | + 'import plotly', |
| 109 | + 'plotly.offline.init_notebook_mode() ' |
| 110 | + '# run at the start of every ipython notebook', |
| 111 | + ])) |
| 112 | + if not tools._ipython_imported: |
| 113 | + raise ImportError('`iplot` can only run inside an IPython Notebook.') |
| 114 | + |
| 115 | + from IPython.display import HTML, display |
| 116 | + if isinstance(figure_or_data, dict): |
| 117 | + data = figure_or_data['data'] |
| 118 | + layout = figure_or_data.get('layout', {}) |
| 119 | + else: |
| 120 | + data = figure_or_data |
| 121 | + layout = {} |
| 122 | + |
| 123 | + width = layout.get('width', '100%') |
| 124 | + height = layout.get('height', 525) |
| 125 | + try: |
| 126 | + float(width) |
| 127 | + except (ValueError, TypeError): |
| 128 | + pass |
| 129 | + else: |
| 130 | + width = str(width) + 'px' |
| 131 | + |
| 132 | + try: |
| 133 | + float(width) |
| 134 | + except (ValueError, TypeError): |
| 135 | + pass |
| 136 | + else: |
| 137 | + width = str(width) + 'px' |
| 138 | + |
| 139 | + plotdivid = uuid.uuid4() |
| 140 | + jdata = json.dumps(data, cls=utils.PlotlyJSONEncoder) |
| 141 | + jlayout = json.dumps(layout, cls=utils.PlotlyJSONEncoder) |
| 142 | + |
| 143 | + if show_link is False: |
| 144 | + link_text = '' |
| 145 | + |
| 146 | + plotly_platform_url = session.get_session_config().get('plotly_domain', |
| 147 | + 'https://plot.ly') |
| 148 | + if (plotly_platform_url != 'https://plot.ly' and |
| 149 | + link_text == 'Export to plot.ly'): |
| 150 | + |
| 151 | + link_domain = plotly_platform_url\ |
| 152 | + .replace('https://', '')\ |
| 153 | + .replace('http://', '') |
| 154 | + link_text = link_text.replace('plot.ly', link_domain) |
| 155 | + |
| 156 | + display(HTML( |
| 157 | + '<script type="text/javascript">' |
| 158 | + 'window.PLOTLYENV={"BASE_URL": "' + plotly_platform_url + '"};' |
| 159 | + 'Plotly.LINKTEXT = "' + link_text + '";' |
| 160 | + '</script>' |
| 161 | + )) |
| 162 | + |
| 163 | + script = '\n'.join([ |
| 164 | + 'Plotly.plot("{id}", {data}, {layout}).then(function() {{', |
| 165 | + ' $(".{id}.loading").remove();', |
| 166 | + '}})' |
| 167 | + ]).format(id=plotdivid, |
| 168 | + data=jdata, |
| 169 | + layout=jlayout, |
| 170 | + link_text=link_text) |
| 171 | + |
| 172 | + display(HTML('' |
| 173 | + '<div class="{id} loading" style="color: rgb(50,50,50);">' |
| 174 | + 'Drawing...</div>' |
| 175 | + '<div id="{id}" style="height: {height}; width: {width};" ' |
| 176 | + 'class="plotly-graph-div">' |
| 177 | + '</div>' |
| 178 | + '<script type="text/javascript">' |
| 179 | + '{script}' |
| 180 | + '</script>' |
| 181 | + ''.format(id=plotdivid, script=script, |
| 182 | + height=height, width=width))) |
| 183 | + |
| 184 | + |
| 185 | +def plot(): |
| 186 | + """ Configured to work with localhost Plotly graph viewer |
| 187 | + """ |
| 188 | + raise NotImplementedError |
| 189 | + |
0 commit comments