Skip to content

Commit 91e74fd

Browse files
committed
Offline: Add load_plotlyjs method to ensure it is always available
1 parent 9caf1c1 commit 91e74fd

File tree

1 file changed

+30
-16
lines changed

1 file changed

+30
-16
lines changed

plotly/offline/offline.py

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,30 @@ def get_plotlyjs():
4848
return plotlyjs
4949

5050

51+
def load_plotlyjs():
52+
"""
53+
Initialize plotly.js in the browser if it hasn't been loaded into the DOM
54+
yet. This is an idempotent method and can and should be called from any
55+
offline methods that require plotly.js to be loaded into the notebook dom.
56+
"""
57+
script_inject = (
58+
''
59+
'<script type=\'text/javascript\'>'
60+
'if(!window.Plotly){{'
61+
'define(\'plotly\', function(require, exports, module) {{'
62+
'{script}'
63+
'}});'
64+
'require([\'plotly\'], function(Plotly) {{'
65+
'console.log(Plotly);'
66+
'window.Plotly = Plotly;'
67+
'}});'
68+
'}}'
69+
'</script>'
70+
'').format(script=get_plotlyjs())
71+
72+
display(HTML(script_inject))
73+
74+
5175
def init_notebook_mode():
5276
"""
5377
Initialize Plotly Offline mode in an IPython Notebook.
@@ -171,25 +195,13 @@ def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly',
171195
172196
Example:
173197
```
174-
from plotly.offline import init_notebook_mode, iplot
175-
init_notebook_mode()
198+
from plotly.offline import, iplot
176199
177200
iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
178201
```
179202
"""
180-
if not __PLOTLY_OFFLINE_INITIALIZED:
181-
raise PlotlyError('\n'.join([
182-
'Plotly Offline mode has not been initialized in this notebook. '
183-
'Run: ',
184-
'',
185-
'import plotly',
186-
'plotly.offline.init_notebook_mode() '
187-
'# run at the start of every ipython notebook',
188-
]))
189-
if not tools._ipython_imported:
190-
raise ImportError('`iplot` can only run inside an IPython Notebook.')
191203

192-
from IPython.display import HTML, display
204+
load_plotlyjs()
193205

194206
plot_html, plotdivid, width, height = _plot_html(
195207
figure_or_data, show_link, link_text, validate,
@@ -434,6 +446,8 @@ def iplot_mpl(mpl_fig, resize=False, strip_style=False,
434446
iplot_mpl(fig)
435447
```
436448
"""
449+
load_plotlyjs()
450+
437451
plotly_plot = tools.mpl_to_plotly(mpl_fig, resize, strip_style, verbose)
438452
return iplot(plotly_plot, show_link, link_text, validate)
439453

@@ -467,8 +481,8 @@ def enable_mpl_offline(resize=False, strip_style=False,
467481
fig
468482
```
469483
"""
470-
if not __PLOTLY_OFFLINE_INITIALIZED:
471-
init_notebook_mode()
484+
load_plotlyjs()
485+
472486
ip = IPython.core.getipython.get_ipython()
473487
formatter = ip.display_formatter.formatters['text/html']
474488
formatter.for_type(matplotlib.figure.Figure,

0 commit comments

Comments
 (0)