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

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
54c96fa
Initial plotly.io.renderers implementation
jonmmease Mar 16, 2019
8342680
rename 'default' to 'plotly_mimetype'
jonmmease Mar 16, 2019
2cc4f89
Added _repr_mimebundle_
jonmmease Mar 16, 2019
28a669c
Add initial browser renderer to show figure in browser tab
jonmmease Mar 16, 2019
8bf793f
Expose renderer base classes
jonmmease Mar 17, 2019
3dfb24a
Documentation / cleanup of _renderers
jonmmease Mar 17, 2019
2dd92c0
Auto-detect VSCode environment and default to renderer combination of
jonmmease Mar 18, 2019
953bae8
Documentation / cleanup of _base_renderers
jonmmease Mar 18, 2019
da39c34
Update default renderers explanation
jonmmease Mar 18, 2019
c2a6471
Add renderer docstring to repr for easy discoverability
jonmmease Mar 18, 2019
e6b9e45
Make ipython an optional dependency
jonmmease Mar 18, 2019
54ac011
Python 2.7 support
jonmmease Mar 18, 2019
7dc1029
Add parent <html></html. tags for HtmlRenderer with fullhtml=True
jonmmease Mar 18, 2019
c23f76e
Added initial renderers test suite
jonmmease Mar 18, 2019
a1d9d9e
Added IFrameRenderer
jonmmease Mar 19, 2019
9d082f0
Proper HTML tags for fullhtml
jonmmease Mar 19, 2019
b499b35
Added initial to_html functions to plotly.io
jonmmease Mar 19, 2019
63424a5
Reimplement plotly.offline.plot using plotly.io.write_html/to_div.
jonmmease Mar 19, 2019
28463c2
Reimplement plotly.offline.iplot and init_notebook_mode pio.show
jonmmease Mar 19, 2019
e4421bb
Add responsive=True config when figure width/height aren't set
jonmmease Mar 19, 2019
3b11783
Add MathJax configuration when initializing HTML renderer in notebook
jonmmease Mar 19, 2019
2580797
Reimplement HTML Renderers using the plotly.io html functions
jonmmease Mar 19, 2019
8a787fd
Restore plot/iplot image export by adding support for custom JS snippets
jonmmease Mar 20, 2019
c4cb4a7
Remove default renderer and make rendering figure on display an option
jonmmease Mar 20, 2019
a109f86
Update renderer tests with plotly.io.renderers.render_on_display
jonmmease Mar 20, 2019
f7f7cb7
Add download image plotly.offline.plot test
jonmmease Mar 20, 2019
f073a14
add set_v3_defaults and set_v4_defaults renderer methods to make
jonmmease Mar 20, 2019
1058683
Added future flag system under _plotly_future_ to control
jonmmease Mar 20, 2019
df3515e
Roll to_div function into to_html with full_html argument
jonmmease Mar 20, 2019
86eb69a
Rename SideEffectRenderer -> ExternalRenderer
jonmmease Mar 21, 2019
c209a18
Fix optional test suite
jonmmease Mar 23, 2019
19de7b9
Use correct config property to grab platform url from saved config
jonmmease Mar 23, 2019
ecf4867
Remove legacy unused _plot_html function
jonmmease Mar 23, 2019
b87ebed
Move static image renderer tests to orca test suite
jonmmease Mar 23, 2019
e11d74f
Move combination renderers test to orca test suite
jonmmease Mar 23, 2019
e8d2f1b
Remove remaining image renderer references from test_io
jonmmease Mar 23, 2019
de80ffc
Add ipython to orca environment for renderer tests
jonmmease Mar 23, 2019
7cba367
Remove pdf image from renderer tests since it seems to be non-determi…
jonmmease Mar 23, 2019
73752d7
Added chromium browser renderer
jonmmease Mar 26, 2019
8a0f6cc
Fix plotly mimetype renderer when used with numpy arrays/pandas Series
jonmmease Mar 26, 2019
504e342
Lazily initialize default renderers.
jonmmease Mar 26, 2019
1115608
Use 'browser' default renderer if ipython isn't available
jonmmease Mar 26, 2019
c647d70
Trigger notebook renderer activation on `init_notebook_mode` call
jonmmease Apr 8, 2019
839f257
Remove whitespace between method calls
jonmmease Apr 9, 2019
18f36b9
review cleanup
jonmmease Apr 9, 2019
5c02ded
simplify to_html logic path
jonmmease Apr 9, 2019
95e2724
Review / cleanup of new renderers
jonmmease Apr 9, 2019
99769cc
Fix json renderer tests
jonmmease Apr 9, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Reimplement plotly.offline.iplot and init_notebook_mode pio.show
  • Loading branch information
jonmmease committed Mar 19, 2019
commit 28463c236bb381bf25d86c05b5e59db14ba7abe1
4 changes: 4 additions & 0 deletions plotly/io/_base_renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ def __repr__(self):
for k in init_args),
doc=self.__doc__)

def __hash__(self):
# Constructor args fully define uniqueness
return hash(repr(self))


class MimetypeRenderer(RendererRepr):
"""
Expand Down
29 changes: 22 additions & 7 deletions plotly/io/_renderers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import absolute_import, division

import textwrap
from copy import copy

import six
import os

Expand Down Expand Up @@ -111,8 +113,10 @@ def default(self):
@default.setter
def default(self, value):
# Handle None
if value is None:
self._default_name = None
if not value:
# _default_name should always be a string so we can do
# pio.renderers.default.split('+')
self._default_name = ''
self._default_renderers = []
return

Expand Down Expand Up @@ -174,7 +178,7 @@ def _available_templates_str(self):
))
return available

def _build_mime_bundle(self, fig_dict, renderers_string=None):
def _build_mime_bundle(self, fig_dict, renderers_string=None, **kwargs):
"""
Build a mime bundle dict containing a kev/value pair for each
MimetypeRenderer specified in either the default renderer string,
Expand Down Expand Up @@ -207,11 +211,17 @@ def _build_mime_bundle(self, fig_dict, renderers_string=None):
bundle = {}
for renderer in renderers_list:
if isinstance(renderer, MimetypeRenderer):
renderer = copy(renderer)
for k, v in kwargs.items():
if hasattr(renderer, k):
setattr(renderer, k, v)

bundle.update(renderer.to_mimebundle(fig_dict))

return bundle

def _perform_side_effect_rendering(self, fig_dict, renderers_string=None):
def _perform_side_effect_rendering(
self, fig_dict, renderers_string=None, **kwargs):
"""
Perform side-effect rendering for each SideEffectRenderer specified
in either the default renderer string, or in the supplied
Expand Down Expand Up @@ -243,6 +253,11 @@ def _perform_side_effect_rendering(self, fig_dict, renderers_string=None):

for renderer in renderers_list:
if isinstance(renderer, SideEffectRenderer):
renderer = copy(renderer)
for k, v in kwargs.items():
if hasattr(renderer, k):
setattr(renderer, k, v)

renderer.render(fig_dict)


Expand All @@ -253,7 +268,7 @@ def _perform_side_effect_rendering(self, fig_dict, renderers_string=None):


# Show
def show(fig, renderer=None, validate=True):
def show(fig, renderer=None, validate=True, **kwargs):
"""
Show a figure using either the default renderer(s) or the renderer(s)
specified by the renderer argument
Expand All @@ -280,7 +295,7 @@ def show(fig, renderer=None, validate=True):

# Mimetype renderers
bundle = renderers._build_mime_bundle(
fig_dict, renderers_string=renderer)
fig_dict, renderers_string=renderer, **kwargs)
if bundle:
if not ipython_display:
raise ValueError(
Expand All @@ -290,7 +305,7 @@ def show(fig, renderer=None, validate=True):

# Side effect renderers
renderers._perform_side_effect_rendering(
fig_dict, renderers_string=renderer)
fig_dict, renderers_string=renderer, **kwargs)


# Register renderers
Expand Down
126 changes: 17 additions & 109 deletions plotly/offline/offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
ipython_display = optional_imports.get_module('IPython.display')
matplotlib = optional_imports.get_module('matplotlib')

__PLOTLY_OFFLINE_INITIALIZED = False

__IMAGE_FORMATS = ['jpeg', 'png', 'webp', 'svg']


Expand Down Expand Up @@ -262,53 +260,15 @@ def init_notebook_mode(connected=False):
your notebook, resulting in much larger notebook sizes compared to the case
where `connected=True`.
"""
import plotly.io as pio

if not ipython:
raise ImportError('`iplot` can only run inside an IPython Notebook.')

global __PLOTLY_OFFLINE_INITIALIZED

if connected:
# Inject plotly.js into the output cell
script_inject = (
'{win_config}'
'{mathjax_config}'
'<script>'
'requirejs.config({{'
'paths: {{ '
# Note we omit the extension .js because require will include it.
'\'plotly\': [\'https://cdn.plot.ly/plotly-latest.min\']}},'
'}});'
'if(!window._Plotly) {{'
'require([\'plotly\'],'
'function(plotly) {{window._Plotly=plotly;}});'
'}}'
'</script>'
).format(win_config=_window_plotly_config,
mathjax_config=_mathjax_config)
pio.renderers.default = 'notebook_connected+plotly_mimetype'
else:
# Inject plotly.js into the output cell
script_inject = (
'{win_config}'
'{mathjax_config}'
'<script type=\'text/javascript\'>'
'require.undef("plotly");'
'define(\'plotly\', function(require, exports, module) {{'
'{script}'
'}});'
'require([\'plotly\'], function(Plotly) {{'
'window._Plotly = Plotly;'
'}});'
'</script>'
'').format(script=get_plotlyjs(),
win_config=_window_plotly_config,
mathjax_config=_mathjax_config)

display_bundle = {
'text/html': script_inject,
'text/vnd.plotly.v1+html': script_inject
}
ipython_display.display(display_bundle, raw=True)
__PLOTLY_OFFLINE_INITIALIZED = True
pio.renderers.default = 'notebook+plotly_mimetype'


def _plot_html(figure_or_data, config, validate, default_width,
Expand Down Expand Up @@ -410,8 +370,8 @@ def _plot_html(figure_or_data, config, validate, default_width,


def iplot(figure_or_data, show_link=False, link_text='Export to plot.ly',
validate=True, image=None, filename='plot_image', image_width=800,
image_height=600, config=None, auto_play=True):
validate=True, image=None, filename=None, image_width=None,
image_height=None, config=None, auto_play=True):
"""
Draw plotly graphs inside an IPython or Jupyter notebook without
connecting to an external server.
Expand All @@ -434,16 +394,8 @@ def iplot(figure_or_data, show_link=False, link_text='Export to plot.ly',
has become outdated with your version of
graph_reference.json or if you need to include
extra, unnecessary keys in your figure.
image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
the format of the image to be downloaded, if we choose to download an
image. This parameter has a default value of None indicating that no
image should be downloaded. Please note: for higher resolution images
and more export options, consider making requests to our image servers.
Type: `help(py.image)` for more details.
filename (default='plot') -- Sets the name of the file your image
will be saved to. The extension should not be included.
image_height (default=600) -- Specifies the height of the image in `px`.
image_width (default=800) -- Specifies the width of the image in `px`.
config (default=None) -- Plot view options dictionary. Keyword arguments
`show_link` and `link_text` set the associated options in this
dictionary if it doesn't contain them already.
Expand All @@ -461,70 +413,26 @@ def iplot(figure_or_data, show_link=False, link_text='Export to plot.ly',
iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png')
```
"""
import plotly.io as pio

if not ipython:
raise ImportError('`iplot` can only run inside an IPython Notebook.')

# Deprecations
if image:
warnings.warn("""
Image export using plotly.offline.plot is no longer supported.
Please use plotly.io.write_image instead""", DeprecationWarning)

config = dict(config) if config else {}
config.setdefault('showLink', show_link)
config.setdefault('linkText', link_text)

jconfig = _get_jconfig(config)

# Get figure
figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)

# Though it can add quite a bit to the display-bundle size, we include
# multiple representations of the plot so that the display environment can
# choose which one to act on.
data = _json.loads(_json.dumps(figure['data'],
cls=plotly.utils.PlotlyJSONEncoder))
layout = _json.loads(_json.dumps(figure.get('layout', {}),
cls=plotly.utils.PlotlyJSONEncoder))
frames = _json.loads(_json.dumps(figure.get('frames', None),
cls=plotly.utils.PlotlyJSONEncoder))

fig = {'data': data, 'layout': layout, 'config': jconfig}
if frames:
fig['frames'] = frames

display_bundle = {'application/vnd.plotly.v1+json': fig}

if __PLOTLY_OFFLINE_INITIALIZED:
plot_html, plotdivid, width, height = _plot_html(
figure_or_data, config, validate, '100%', 525, True, auto_play)
resize_script = ''
if width == '100%' or height == '100%':
resize_script = _build_resize_script(
plotdivid, 'window._Plotly')

display_bundle['text/html'] = plot_html + resize_script
display_bundle['text/vnd.plotly.v1+html'] = plot_html + resize_script

ipython_display.display(display_bundle, raw=True)

if image:
if not __PLOTLY_OFFLINE_INITIALIZED:
raise PlotlyError('\n'.join([
'Plotly Offline mode has not been initialized in this notebook. '
'Run: ',
'',
'import plotly',
'plotly.offline.init_notebook_mode() '
'# run at the start of every ipython notebook',
]))
if image not in __IMAGE_FORMATS:
raise ValueError('The image parameter must be one of the following'
': {}'.format(__IMAGE_FORMATS)
)
# if image is given, and is a valid format, we will download the image
script = get_image_download_script('iplot').format(format=image,
width=image_width,
height=image_height,
filename=filename,
plot_id=plotdivid)
# allow time for the plot to draw
time.sleep(1)
# inject code to download an image of the plot
ipython_display.display(ipython_display.HTML(script))
# Show figure
pio.show(figure, validate=validate, config=config, auto_play=auto_play)


def plot(figure_or_data, show_link=False, link_text='Export to plot.ly',
Expand Down