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 Parameters ---------- fig: dict of Figure The Figure object or figure dict to display renderer: str or None (default None) A string containing the names of one or more registered renderers (separated by '+' characters) or None. If None, then the default renderers specified in plotly.io.renderers.default are used. validate: bool (default True) True if the figure should be validated before being shown, False otherwise. width: int or float An integer or float that determines the number of pixels wide the plot is. The default is set in plotly.js. height: int or float An integer or float that determines the number of pixels wide the plot is. The default is set in plotly.js. config: dict A dict of parameters to configure the figure. The defaults are set in plotly.js. Returns ------- None """ fig_dict = validate_coerce_fig_to_dict(fig, validate) # Mimetype renderers bundle = renderers._build_mime_bundle(fig_dict, renderers_string=renderer, **kwargs) if bundle: if not ipython_display: raise ValueError( "Mime type rendering requires ipython but it is not installed") if not nbformat or LooseVersion( nbformat.__version__) < LooseVersion("4.2.0"): raise ValueError( "Mime type rendering requires nbformat>=4.2.0 but it is not installed" ) ipython_display.display(bundle, raw=True) # external renderers renderers._perform_external_rendering(fig_dict, renderers_string=renderer, **kwargs)
def to_json(fig, validate=True, pretty=False, remove_uids=True): """ Convert a figure to a JSON string representation Parameters ---------- fig: Figure object or dict representing a figure validate: bool (default True) True if the figure should be validated before being converted to JSON, False otherwise. pretty: bool (default False) True if JSON representation should be pretty-printed, False if representation should be as compact as possible. remove_uids: bool (default True) True if trace UIDs should be omitted from the JSON representation Returns ------- str Representation of figure as a JSON string """ from _plotly_utils.utils import PlotlyJSONEncoder # Validate figure # --------------- fig_dict = validate_coerce_fig_to_dict(fig, validate) # Remove trace uid # ---------------- if remove_uids: for trace in fig_dict.get('data', []): trace.pop('uid', None) # Dump to a JSON string and return # -------------------------------- opts = {'sort_keys': True} if pretty: opts['indent'] = 2 else: # Remove all whitespace opts['separators'] = (',', ':') return json.dumps(fig_dict, cls=PlotlyJSONEncoder, **opts)
def to_mimebundle(self, fig): fig_dict = validate_coerce_fig_to_dict(fig, True) divid = str(uuid.uuid4()) data = fig_dict.get("data", []) jdata = json.dumps(data, cls=PlotlyJSONEncoder, sort_keys=True) layout = fig_dict.get("layout", {}) jlayout = json.dumps(layout, cls=PlotlyJSONEncoder, sort_keys=True) config = _get_jconfig(None) config.setdefault("responsive", True) jconfig = json.dumps(config) script = f'render_plot({{divid: "{divid}", layout: {jlayout}, config: {jconfig}' script += f', tid: "{self.tid}", data: {jdata}}})' html = f'<div><div id="{divid}"></div>' html += f'<script type="text/javascript">{script};</script></div>' return {"text/html": html}
def to_json(fig, validate=True, pretty=False, remove_uids=True, engine=None): """ Convert a figure to a JSON string representation Parameters ---------- fig: Figure object or dict representing a figure validate: bool (default True) True if the figure should be validated before being converted to JSON, False otherwise. pretty: bool (default False) True if JSON representation should be pretty-printed, False if representation should be as compact as possible. remove_uids: bool (default True) True if trace UIDs should be omitted from the JSON representation engine: str (default None) The JSON encoding engine to use. One of: - "json" for an engine based on the built-in Python json module - "orjson" for a faster engine that requires the orjson package - "auto" for the "orjson" engine if available, otherwise "json" If not specified, the default engine is set to the current value of plotly.io.json.config.default_engine. Returns ------- str Representation of figure as a JSON string See Also -------- to_json_plotly : Convert an arbitrary plotly graph_object or Dash component to JSON """ # Validate figure # --------------- fig_dict = validate_coerce_fig_to_dict(fig, validate) # Remove trace uid # ---------------- if remove_uids: for trace in fig_dict.get("data", []): trace.pop("uid", None) return to_json_plotly(fig_dict, pretty=pretty, engine=engine)
def to_mimebundle(self, fig): fig_dict = validate_coerce_fig_to_dict(fig, True) divid = str(uuid.uuid4()) data = fig_dict.get('data', []) jdata = json.dumps(data, cls=PlotlyJSONEncoder, sort_keys=True) layout = fig_dict.get('layout', {}) jlayout = json.dumps(layout, cls=PlotlyJSONEncoder, sort_keys=True) config = _get_jconfig(None) config.setdefault('responsive', True) jconfig = json.dumps(config) script = f'render_plot({{\ divid: "{divid}", data: {jdata}, layout: {jlayout}, config: {jconfig}\ }})' html = f'<div><div id="{divid}"></div>' html += f'<script type="text/javascript">{script};</script></div>' return {'text/html': html}
def to_json(fig, validate=True, pretty=False, remove_uids=True): """ Convert a figure to a JSON string representation Parameters ---------- fig: Figure object or dict representing a figure validate: bool (default True) True if the figure should be validated before being converted to JSON, False otherwise. pretty: bool (default False) True if JSON representation should be pretty-printed, False if representation should be as compact as possible. remove_uids: bool (default True) True if trace UIDs should be omitted from the JSON representation Returns ------- str Representation of figure as a JSON string """ from _plotly_utils.utils import PlotlyJSONEncoder # Validate figure # --------------- fig_dict = validate_coerce_fig_to_dict(fig, validate) # Remove trace uid # ---------------- if remove_uids: for trace in fig_dict.get('data', []): trace.pop('uid', None) # Dump to a JSON string and return # -------------------------------- opts = {'sort_keys': True} if pretty: opts['indent'] = 2 else: # Remove all whitespace opts['separators'] = (',', ':') return json.dumps(fig_dict, cls=PlotlyJSONEncoder, **opts)
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 Parameters ---------- fig: dict of Figure The Figure object or figure dict to display renderer: str or None (default None) A string containing the names of one or more registered renderers (separated by '+' characters) or None. If None, then the default renderers specified in plotly.io.renderers.default are used. validate: bool (default True) True if the figure should be validated before being shown, False otherwise. Returns ------- None """ fig_dict = validate_coerce_fig_to_dict(fig, validate) # Mimetype renderers bundle = renderers._build_mime_bundle(fig_dict, renderers_string=renderer, **kwargs) if bundle: if not ipython_display: raise ValueError( 'Mime type rendering requires ipython but it is not installed') ipython_display.display(bundle, raw=True) # external renderers renderers._perform_external_rendering(fig_dict, renderers_string=renderer, **kwargs)
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 Parameters ---------- fig: dict of Figure The Figure object or figure dict to display renderer: str or None (default None) A string containing the names of one or more registered renderers (separated by '+' characters) or None. If None, then the default renderers specified in plotly.io.renderers.default are used. validate: bool (default True) True if the figure should be validated before being shown, False otherwise. Returns ------- None """ fig_dict = validate_coerce_fig_to_dict(fig, validate) # Mimetype renderers bundle = renderers._build_mime_bundle( fig_dict, renderers_string=renderer, **kwargs) if bundle: if not ipython_display: raise ValueError( 'Mime type rendering requires ipython but it is not installed') ipython_display.display(bundle, raw=True) # external renderers renderers._perform_external_rendering( fig_dict, renderers_string=renderer, **kwargs)
def to_html(fig, config=None, auto_play=True, include_plotlyjs=True, include_mathjax=False, post_script=None, full_html=True, animation_opts=None, default_width='100%', default_height='100%', validate=True): """ Convert a figure to an HTML string representation. Parameters ---------- fig: Figure object or dict representing a figure config: dict or None (default None) Plotly.js figure config options auto_play: bool (default=True) Whether to automatically start the animation sequence on page load if the figure contains frames. Has no effect if the figure does not contain frames. include_plotlyjs: bool or string (default True) Specifies how the plotly.js library is included/loaded in the output div string. If True, a script tag containing the plotly.js source code (~3MB) is included in the output. HTML files generated with this option are fully self-contained and can be used offline. If 'cdn', a script tag that references the plotly.js CDN is included in the output. HTML files generated with this option are about 3MB smaller than those generated with include_plotlyjs=True, but they require an active internet connection in order to load the plotly.js library. If 'directory', a script tag is included that references an external plotly.min.js bundle that is assumed to reside in the same directory as the HTML file. If 'require', Plotly.js is loaded using require.js. This option assumes that require.js is globally available and that it has been globally configured to know how to find Plotly.js as 'plotly'. This option is not advised when full_html=True as it will result in a non-functional html file. If a string that ends in '.js', a script tag is included that references the specified path. This approach can be used to point the resulting HTML file to an alternative CDN or local bundle. If False, no script tag referencing plotly.js is included. This is useful when the resulting div string will be placed inside an HTML document that already loads plotly.js. This option is not advised when full_html=True as it will result in a non-functional html file. include_mathjax: bool or string (default False) Specifies how the MathJax.js library is included in the output html div string. MathJax is required in order to display labels with LaTeX typesetting. If False, no script tag referencing MathJax.js will be included in the output. If 'cdn', a script tag that references a MathJax CDN location will be included in the output. HTML div strings generated with this option will be able to display LaTeX typesetting as long as internet access is available. If a string that ends in '.js', a script tag is included that references the specified path. This approach can be used to point the resulting HTML div string to an alternative CDN. post_script: str or list or None (default None) JavaScript snippet(s) to be included in the resulting div just after plot creation. The string(s) may include '{plot_id}' placeholders that will then be replaced by the `id` of the div element that the plotly.js figure is associated with. One application for this script is to install custom plotly.js event handlers. full_html: bool (default True) If True, produce a string containing a complete HTML document starting with an <html> tag. If False, produce a string containing a single <div> element. animation_opts: dict or None (default None) dict of custom animation parameters to be passed to the function Plotly.animate in Plotly.js. See https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js for available options. Has no effect if the figure does not contain frames, or auto_play is False. default_width, default_height: number or str (default '100%') The default figure width/height to use if the provided figure does not specify its own layout.width/layout.height property. May be specified in pixels as an integer (e.g. 500), or as a css width style string (e.g. '500px', '100%'). validate: bool (default True) True if the figure should be validated before being converted to JSON, False otherwise. Returns ------- str Representation of figure as an HTML div string """ # ## Validate figure ## fig_dict = validate_coerce_fig_to_dict(fig, validate) # ## Generate div id ## plotdivid = str(uuid.uuid4()) # ## Serialize figure ## jdata = json.dumps(fig_dict.get('data', []), cls=utils.PlotlyJSONEncoder, sort_keys=True) jlayout = json.dumps(fig_dict.get('layout', {}), cls=utils.PlotlyJSONEncoder, sort_keys=True) if fig_dict.get('frames', None): jframes = json.dumps(fig_dict.get('frames', []), cls=utils.PlotlyJSONEncoder) else: jframes = None # ## Serialize figure config ## config = _get_jconfig(config) # Set responsive config.setdefault('responsive', True) jconfig = json.dumps(config) # Get div width/height layout_dict = fig_dict.get('layout', {}) template_dict = (fig_dict.get('layout', {}).get('template', {}).get('layout', {})) div_width = layout_dict.get('width', template_dict.get('width', default_width)) div_height = layout_dict.get('height', template_dict.get('height', default_height)) # Add 'px' suffix to numeric widths try: float(div_width) except (ValueError, TypeError): pass else: div_width = str(div_width) + 'px' try: float(div_height) except (ValueError, TypeError): pass else: div_height = str(div_height) + 'px' # ## Get platform URL ## plotly_platform_url = config.get('plotlyServerURL', 'https://plot.ly') # ## Build script body ## # This is the part that actually calls Plotly.js # build post script snippet(s) then_post_script = '' if post_script: if not isinstance(post_script, (list, tuple)): post_script = [post_script] for ps in post_script: then_post_script += """.then(function(){{ {post_script} }})""".format( post_script=ps.replace('{plot_id}', plotdivid)) then_addframes = '' then_animate = '' if jframes: then_addframes = """.then(function(){{ Plotly.addFrames('{id}', {frames}); }})""".format(id=plotdivid, frames=jframes) if auto_play: if animation_opts: animation_opts_arg = ', ' + json.dumps(animation_opts) else: animation_opts_arg = '' then_animate = """.then(function(){{ Plotly.animate('{id}', null{animation_opts}); }})""".format(id=plotdivid, animation_opts=animation_opts_arg) script = """ if (document.getElementById("{id}")) {{ Plotly.newPlot( '{id}', {data}, {layout}, {config} ){then_addframes}{then_animate}{then_post_script} }}""".format(id=plotdivid, data=jdata, layout=jlayout, config=jconfig, then_addframes=then_addframes, then_animate=then_animate, then_post_script=then_post_script) # ## Handle loading/initializing plotly.js ## include_plotlyjs_orig = include_plotlyjs if isinstance(include_plotlyjs, six.string_types): include_plotlyjs = include_plotlyjs.lower() # Start/end of requirejs block (if any) require_start = '' require_end = '' # Init and load load_plotlyjs = '' # Init plotlyjs. This block needs to run before plotly.js is loaded in # order for MathJax configuration to work properly if include_plotlyjs == 'require': require_start = 'require(["plotly"], function(Plotly) {' require_end = '});' elif include_plotlyjs == 'cdn': load_plotlyjs = """\ {win_config} <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>\ """.format(win_config=_window_plotly_config) elif include_plotlyjs == 'directory': load_plotlyjs = """\ {win_config} <script src="plotly.min.js"></script>\ """.format(win_config=_window_plotly_config) elif (isinstance(include_plotlyjs, six.string_types) and include_plotlyjs.endswith('.js')): load_plotlyjs = """\ {win_config} <script src="{url}"></script>\ """.format(win_config=_window_plotly_config, url=include_plotlyjs_orig) elif include_plotlyjs: load_plotlyjs = """\ {win_config} <script type="text/javascript">{plotlyjs}</script>\ """.format(win_config=_window_plotly_config, plotlyjs=get_plotlyjs()) # ## Handle loading/initializing MathJax ## include_mathjax_orig = include_mathjax if isinstance(include_mathjax, six.string_types): include_mathjax = include_mathjax.lower() mathjax_template = """\ <script src="{url}?config=TeX-AMS-MML_SVG"></script>""" if include_mathjax == 'cdn': mathjax_script = mathjax_template.format( url=('https://cdnjs.cloudflare.com' '/ajax/libs/mathjax/2.7.5/MathJax.js')) + _mathjax_config elif (isinstance(include_mathjax, six.string_types) and include_mathjax.endswith('.js')): mathjax_script = mathjax_template.format( url=include_mathjax_orig) + _mathjax_config elif not include_mathjax: mathjax_script = '' else: raise ValueError("""\ Invalid value of type {typ} received as the include_mathjax argument Received value: {val} include_mathjax may be specified as False, 'cdn', or a string ending with '.js' """.format(typ=type(include_mathjax), val=repr(include_mathjax))) plotly_html_div = """\ <div> {mathjax_script} {load_plotlyjs} <div id="{id}" class="plotly-graph-div" \ style="height:{height}; width:{width};"></div> <script type="text/javascript"> {require_start} window.PLOTLYENV=window.PLOTLYENV || {{}}; window.PLOTLYENV.BASE_URL='{plotly_platform_url}'; {script}; {require_end} </script> </div>""".format(mathjax_script=mathjax_script, load_plotlyjs=load_plotlyjs, id=plotdivid, width=div_width, height=div_height, plotly_platform_url=plotly_platform_url, require_start=require_start, script=script, require_end=require_end) if full_html: return """\ <html> <head><meta charset="utf-8" /></head> <body> {div} </body> </html>""".format(div=plotly_html_div) else: return plotly_html_div
def wrapped( fig: Union[Figure, dict], renderer: str = None, validate: bool = True, **kwargs: Dict[str, Any] ) -> None: validate_coerce_fig_to_dict(fig, validate)
def to_image(fig, format=None, width=None, height=None, scale=None, validate=True): """ Convert a figure to a static image bytes string Parameters ---------- fig: Figure object or dict representing a figure format: str or None The desired image format. One of - 'png' - 'jpg' or 'jpeg' - 'webp' - 'svg' - 'pdf' - 'eps' (Requires the poppler library to be installed) If not specified, will default to `plotly.io.config.default_format` width: int or None The width of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the width of the exported image in physical pixels. If not specified, will default to `plotly.io.config.default_width` height: int or None The height of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the height of the exported image in physical pixels. If not specified, will default to `plotly.io.config.default_height` scale: int or float or None The scale factor to use when exporting the figure. A scale factor larger than 1.0 will increase the image resolution with respect to the figure's layout pixel dimensions. Whereas as scale factor of less than 1.0 will decrease the image resolution. If not specified, will default to `plotly.io.config.default_scale` validate: bool True if the figure should be validated before being converted to an image, False otherwise. Returns ------- bytes The image data """ # Make sure orca sever is running # ------------------------------- ensure_server() # Handle defaults # --------------- # Apply configuration defaults to unspecified arguments if format is None: format = config.default_format format = validate_coerce_format(format) if scale is None: scale = config.default_scale if width is None: width = config.default_width if height is None: height = config.default_height # Validate figure # --------------- fig_dict = validate_coerce_fig_to_dict(fig, validate) # Request image from server # ------------------------- try: response = request_image_with_retrying( figure=fig_dict, format=format, scale=scale, width=width, height=height) except OSError as err: # Get current status string status_str = repr(status) # Check if the orca server process exists pid_exists = psutil.pid_exists(status.pid) # Raise error message based on whether the server process existed if pid_exists: raise ValueError(""" For some reason plotly.py was unable to communicate with the local orca server process, even though the server process seems to be running. Please review the process and connection information below: {info} """.format(info=status_str)) else: # Reset the status so that if the user tries again, we'll try to # start the server again reset_status() raise ValueError(""" For some reason the orca server process is no longer running. Please review the process and connection information below: {info} plotly.py will attempt to start the local server process again the next time an image export operation is performed. """.format(info=status_str)) # Check response # -------------- if response.status_code == 200: # All good return response.content else: # ### Something went wrong ### err_message = """ The image request was rejected by the orca conversion utility with the following error: {status}: {msg} """.format(status=response.status_code, msg=response.content.decode('utf-8')) # ### Try to be helpful ### # Status codes from /src/component/plotly-graph/constants.js in the # orca code base. # statusMsg: { # 400: 'invalid or malformed request syntax', # 525: 'plotly.js error', # 526: 'plotly.js version 1.11.0 or up required', # 530: 'image conversion error' # } if (response.status_code == 400 and isinstance(fig, dict) and not validate): err_message += """ Try setting the `validate` argument to True to check for errors in the figure specification""" elif response.status_code == 525: any_mapbox = any([trace.get('type', None) == 'scattermapbox' for trace in fig_dict.get('data', [])]) if any_mapbox and config.mapbox_access_token is None: err_message += """ Exporting scattermapbox traces requires a mapbox access token. Create a token in your mapbox account and then set it using: >>> plotly.io.orca.config.mapbox_access_token = 'pk.abc...' If you would like this token to be applied automatically in future sessions, then save your orca configuration as follows: >>> plotly.io.orca.config.save() """ elif response.status_code == 530 and format == 'eps': err_message += """ Exporting to EPS format requires the poppler library. You can install poppler on MacOS or Linux with: $ conda install poppler Or, you can install it on MacOS using homebrew with: $ brew install poppler Or, you can install it on Linux using your distribution's package manager to install the 'poppler-utils' package. Unfortunately, we don't yet know of an easy way to install poppler on Windows. """ raise ValueError(err_message)
def to_image(fig, format=None, width=None, height=None, scale=None, validate=True): """ Convert a figure to a static image bytes string Parameters ---------- fig: Figure object or dict representing a figure format: str or None The desired image format. One of - 'png' - 'jpg' or 'jpeg' - 'webp' - 'svg' - 'pdf' - 'eps' (Requires the poppler library to be installed) If not specified, will default to `plotly.io.config.default_format` width: int or None The width of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the width of the exported image in physical pixels. If not specified, will default to `plotly.io.config.default_width` height: int or None The height of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the height of the exported image in physical pixels. If not specified, will default to `plotly.io.config.default_height` scale: int or float or None The scale factor to use when exporting the figure. A scale factor larger than 1.0 will increase the image resolution with respect to the figure's layout pixel dimensions. Whereas as scale factor of less than 1.0 will decrease the image resolution. If not specified, will default to `plotly.io.config.default_scale` validate: bool True if the figure should be validated before being converted to an image, False otherwise. Returns ------- bytes The image data """ # Make sure orca sever is running # ------------------------------- ensure_server() # Handle defaults # --------------- # Apply configuration defaults to unspecified arguments if format is None: format = config.default_format format = validate_coerce_format(format) if scale is None: scale = config.default_scale if width is None: width = config.default_width if height is None: height = config.default_height # Validate figure # --------------- fig_dict = validate_coerce_fig_to_dict(fig, validate) # Request image from server # ------------------------- try: response = request_image_with_retrying(figure=fig_dict, format=format, scale=scale, width=width, height=height) except OSError as err: # Get current status string status_str = repr(status) # Check if the orca server process exists pid_exists = psutil.pid_exists(status.pid) # Raise error message based on whether the server process existed if pid_exists: raise ValueError(""" For some reason plotly.py was unable to communicate with the local orca server process, even though the server process seems to be running. Please review the process and connection information below: {info} """.format(info=status_str)) else: # Reset the status so that if the user tries again, we'll try to # start the server again reset_status() raise ValueError(""" For some reason the orca server process is no longer running. Please review the process and connection information below: {info} plotly.py will attempt to start the local server process again the next time an image export operation is performed. """.format(info=status_str)) # Check response # -------------- if response.status_code == 200: # All good return response.content else: # ### Something went wrong ### err_message = """ The image request was rejected by the orca conversion utility with the following error: {status}: {msg} """.format(status=response.status_code, msg=response.content.decode("utf-8")) # ### Try to be helpful ### # Status codes from /src/component/plotly-graph/constants.js in the # orca code base. # statusMsg: { # 400: 'invalid or malformed request syntax', # 522: client socket timeout # 525: 'plotly.js error', # 526: 'plotly.js version 1.11.0 or up required', # 530: 'image conversion error' # } if response.status_code == 400 and isinstance(fig, dict) and not validate: err_message += """ Try setting the `validate` argument to True to check for errors in the figure specification""" elif response.status_code == 525: any_mapbox = any( trace.get("type", None) == "scattermapbox" for trace in fig_dict.get("data", [])) if any_mapbox and config.mapbox_access_token is None: err_message += """ Exporting scattermapbox traces requires a mapbox access token. Create a token in your mapbox account and then set it using: >>> plotly.io.orca.config.mapbox_access_token = 'pk.abc...' If you would like this token to be applied automatically in future sessions, then save your orca configuration as follows: >>> plotly.io.orca.config.save() """ elif response.status_code == 530 and format == "eps": err_message += """ Exporting to EPS format requires the poppler library. You can install poppler on MacOS or Linux with: $ conda install poppler Or, you can install it on MacOS using homebrew with: $ brew install poppler Or, you can install it on Linux using your distribution's package manager to install the 'poppler-utils' package. Unfortunately, we don't yet know of an easy way to install poppler on Windows. """ raise ValueError(err_message)
def to_image(fig, format=None, width=None, height=None, scale=None, validate=True, engine="auto"): """ Convert a figure to a static image bytes string Parameters ---------- fig: Figure object or dict representing a figure format: str or None The desired image format. One of - 'png' - 'jpg' or 'jpeg' - 'webp' - 'svg' - 'pdf' - 'eps' (Requires the poppler library to be installed and on the PATH) If not specified, will default to: - `plotly.io.kaleido.scope.default_format` if engine is "kaleido" - `plotly.io.orca.config.default_format` if engine is "orca" width: int or None The width of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the width of the exported image in physical pixels. If not specified, will default to: - `plotly.io.kaleido.scope.default_width` if engine is "kaleido" - `plotly.io.orca.config.default_width` if engine is "orca" height: int or None The height of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the height of the exported image in physical pixels. If not specified, will default to: - `plotly.io.kaleido.scope.default_height` if engine is "kaleido" - `plotly.io.orca.config.default_height` if engine is "orca" scale: int or float or None The scale factor to use when exporting the figure. A scale factor larger than 1.0 will increase the image resolution with respect to the figure's layout pixel dimensions. Whereas as scale factor of less than 1.0 will decrease the image resolution. If not specified, will default to: - `plotly.io.kaleido.scope.default_scale` if engine is "kaleido" - `plotly.io.orca.config.default_scale` if engine is "orca" validate: bool True if the figure should be validated before being converted to an image, False otherwise. engine: str Image export engine to use: - "kaleido": Use Kaleido for image export - "orca": Use Orca for image export - "auto" (default): Use Kaleido if installed, otherwise use orca Returns ------- bytes The image data """ # Handle engine # ------------- if engine == "auto": if scope is not None: # Default to kaleido if available engine = "kaleido" else: # See if orca is available from ._orca import validate_executable try: validate_executable() engine = "orca" except: # If orca not configured properly, make sure we display the error # message advising the installation of kaleido engine = "kaleido" if engine == "orca": # Fall back to legacy orca image export path from ._orca import to_image as to_image_orca return to_image_orca( fig, format=format, width=width, height=height, scale=scale, validate=validate, ) elif engine != "kaleido": raise ValueError( "Invalid image export engine specified: {engine}".format( engine=repr(engine))) # Raise informative error message if Kaleido is not installed if scope is None: raise ValueError(""" Image export using the "kaleido" engine requires the kaleido package, which can be installed using pip: $ pip install -U kaleido """) # Validate figure # --------------- fig_dict = validate_coerce_fig_to_dict(fig, validate) img_bytes = scope.transform(fig_dict, format=format, width=width, height=height, scale=scale) return img_bytes
def to_html( fig, config=None, auto_play=True, include_plotlyjs=True, include_mathjax=False, post_script=None, full_html=True, animation_opts=None, default_width="100%", default_height="100%", validate=True, compress=True, ): """ Convert a figure to an HTML string representation. Parameters ---------- fig: Figure object or dict representing a figure config: dict or None (default None) Plotly.js figure config options auto_play: bool (default=True) Whether to automatically start the animation sequence on page load if the figure contains frames. Has no effect if the figure does not contain frames. include_plotlyjs: bool or string (default True) Specifies how the plotly.js library is included/loaded in the output div string. If True, a script tag containing the plotly.js source code (~3MB) is included in the output. HTML files generated with this option are fully self-contained and can be used offline. If 'cdn', a script tag that references the plotly.js CDN is included in the output. HTML files generated with this option are about 3MB smaller than those generated with include_plotlyjs=True, but they require an active internet connection in order to load the plotly.js library. If 'directory', a script tag is included that references an external plotly.min.js bundle that is assumed to reside in the same directory as the HTML file. If 'require', Plotly.js is loaded using require.js. This option assumes that require.js is globally available and that it has been globally configured to know how to find Plotly.js as 'plotly'. This option is not advised when full_html=True as it will result in a non-functional html file. If a string that ends in '.js', a script tag is included that references the specified path. This approach can be used to point the resulting HTML file to an alternative CDN or local bundle. If False, no script tag referencing plotly.js is included. This is useful when the resulting div string will be placed inside an HTML document that already loads plotly.js. This option is not advised when full_html=True as it will result in a non-functional html file. include_mathjax: bool or string (default False) Specifies how the MathJax.js library is included in the output html div string. MathJax is required in order to display labels with LaTeX typesetting. If False, no script tag referencing MathJax.js will be included in the output. If 'cdn', a script tag that references a MathJax CDN location will be included in the output. HTML div strings generated with this option will be able to display LaTeX typesetting as long as internet access is available. If a string that ends in '.js', a script tag is included that references the specified path. This approach can be used to point the resulting HTML div string to an alternative CDN. post_script: str or list or None (default None) JavaScript snippet(s) to be included in the resulting div just after plot creation. The string(s) may include '{plot_id}' placeholders that will then be replaced by the `id` of the div element that the plotly.js figure is associated with. One application for this script is to install custom plotly.js event handlers. full_html: bool (default True) If True, produce a string containing a complete HTML document starting with an <html> tag. If False, produce a string containing a single <div> element. animation_opts: dict or None (default None) dict of custom animation parameters to be passed to the function Plotly.animate in Plotly.js. See https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js for available options. Has no effect if the figure does not contain frames, or auto_play is False. default_width, default_height: number or str (default '100%') The default figure width/height to use if the provided figure does not specify its own layout.width/layout.height property. May be specified in pixels as an integer (e.g. 500), or as a css width style string (e.g. '500px', '100%'). validate: bool (default True) True if the figure should be validated before being converted to JSON, False otherwise. compress: bool (default False) If True, the figure data is compressed reducing the total file size. It adds an external compression library which requires an active internet connection. Returns ------- str Representation of figure as an HTML div string """ # ## Validate figure ## fig_dict = validate_coerce_fig_to_dict(fig, validate) # ## Generate div id ## plotdivid = str(uuid.uuid4()) # ## Serialize figure ## jdata = json.dumps(fig_dict.get("data", []), cls=utils.PlotlyJSONEncoder, sort_keys=True) jlayout = json.dumps(fig_dict.get("layout", {}), cls=utils.PlotlyJSONEncoder, sort_keys=True) if fig_dict.get("frames", None): jframes = json.dumps(fig_dict.get("frames", []), cls=utils.PlotlyJSONEncoder) else: jframes = None # ## Serialize figure config ## config = _get_jconfig(config) # Set responsive config.setdefault("responsive", True) # Get div width/height layout_dict = fig_dict.get("layout", {}) template_dict = fig_dict.get("layout", {}).get("template", {}).get("layout", {}) div_width = layout_dict.get("width", template_dict.get("width", default_width)) div_height = layout_dict.get("height", template_dict.get("height", default_height)) # Add 'px' suffix to numeric widths try: float(div_width) except (ValueError, TypeError): pass else: div_width = str(div_width) + "px" try: float(div_height) except (ValueError, TypeError): pass else: div_height = str(div_height) + "px" # ## Get platform URL ## if config.get("showLink", False) or config.get("showSendToCloud", False): # Figure is going to include a Chart Studio link or send-to-cloud button, # So we need to configure the PLOTLYENV.BASE_URL property base_url_line = """ window.PLOTLYENV.BASE_URL='{plotly_platform_url}';\ """.format(plotly_platform_url=config.get("plotlyServerURL", "https://plot.ly")) else: # Figure is not going to include a Chart Studio link or send-to-cloud button, # In this case we don't want https://plot.ly to show up anywhere in the HTML # output config.pop("plotlyServerURL", None) config.pop("linkText", None) config.pop("showLink", None) base_url_line = "" # ## Build script body ## # This is the part that actually calls Plotly.js # build post script snippet(s) then_post_script = "" if post_script: if not isinstance(post_script, (list, tuple)): post_script = [post_script] for ps in post_script: then_post_script += """.then(function(){{ {post_script} }})""".format( post_script=ps.replace("{plot_id}", plotdivid)) then_addframes = "" then_animate = "" script_compressed_frames = "" if jframes: # If compression is enabled, then add zipped data decompress before Plotly is called. if compress: frames_compr_b64 = base64.b64encode( gzip.compress(jframes.encode('utf-8'))).decode('ascii') script_compressed_frames = """\ const frames_compr_b64 = "{frames_compr_b64}"; const frames_raw = fflate.decompressSync( fflate.strToU8(atob(frames_compr_b64), true) ); const frames = JSON.parse(fflate.strFromU8(frames_raw)); """.format(frames_compr_b64=frames_compr_b64) # Replace jframes with variable named `frames` jframes = "frames" then_addframes = """.then(function(){{ Plotly.addFrames('{id}', {frames}); }})""".format(id=plotdivid, frames=jframes) if auto_play: if animation_opts: animation_opts_arg = ", " + json.dumps(animation_opts) else: animation_opts_arg = "" then_animate = """.then(function(){{ Plotly.animate('{id}', null{animation_opts}); }})""".format(id=plotdivid, animation_opts=animation_opts_arg) # Serialize config dict to JSON jconfig = json.dumps(config) # Compress data via fflate and use a variable "data" to store the unpacked. script_compress = "" if compress: compressed_data = base64.b64encode(gzip.compress( jdata.encode('utf-8'))).decode('ascii') script_compress = """\ const data_compr_b64 = "{compressed_data}"; const data_raw = fflate.decompressSync( fflate.strToU8(atob(data_compr_b64), true) ); const data = JSON.parse(fflate.strFromU8(data_raw)); """.format(compressed_data=compressed_data) # Replace the plotly data with the variable "data". jdata = "data" script = """\ if (document.getElementById("{id}")) {{\ {script_compress}\ {script_compressed_frames}\ Plotly.newPlot(\ "{id}",\ {data},\ {layout},\ {config}\ ){then_addframes}{then_animate}{then_post_script}\ }}""".format( id=plotdivid, data=jdata, script_compress=script_compress, script_compressed_frames=script_compressed_frames, layout=jlayout, config=jconfig, then_addframes=then_addframes, then_animate=then_animate, then_post_script=then_post_script, ) # ## Handle loading/initializing plotly.js ## include_plotlyjs_orig = include_plotlyjs if isinstance(include_plotlyjs, six.string_types): include_plotlyjs = include_plotlyjs.lower() # Start/end of requirejs block (if any) require_start = "" require_end = "" # Init and load load_plotlyjs = "" # Init plotlyjs. This block needs to run before plotly.js is loaded in # order for MathJax configuration to work properly if include_plotlyjs == "require": require_start = 'require(["plotly"], function(Plotly) {' require_end = "});" elif include_plotlyjs == "cdn": load_plotlyjs = """\ {win_config} <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>\ """.format(win_config=_window_plotly_config) elif include_plotlyjs == "directory": load_plotlyjs = """\ {win_config} <script src="plotly.min.js"></script>\ """.format(win_config=_window_plotly_config) elif isinstance(include_plotlyjs, six.string_types) and include_plotlyjs.endswith(".js"): load_plotlyjs = """\ {win_config} <script src="{url}"></script>\ """.format(win_config=_window_plotly_config, url=include_plotlyjs_orig) elif include_plotlyjs: load_plotlyjs = """\ {win_config} <script type="text/javascript">{plotlyjs}</script>\ """.format(win_config=_window_plotly_config, plotlyjs=get_plotlyjs()) load_fflatejs = "" if compress: load_fflatejs = "<script src=\"https://cdn.jsdelivr.net/npm/[email protected]/umd/index.min.js\"></script>" # ## Handle loading/initializing MathJax ## include_mathjax_orig = include_mathjax if isinstance(include_mathjax, six.string_types): include_mathjax = include_mathjax.lower() mathjax_template = """\ <script src="{url}?config=TeX-AMS-MML_SVG"></script>""" if include_mathjax == "cdn": mathjax_script = (mathjax_template.format( url=("https://cdnjs.cloudflare.com" "/ajax/libs/mathjax/2.7.5/MathJax.js")) + _mathjax_config) elif isinstance(include_mathjax, six.string_types) and include_mathjax.endswith(".js"): mathjax_script = (mathjax_template.format(url=include_mathjax_orig) + _mathjax_config) elif not include_mathjax: mathjax_script = "" else: raise ValueError("""\ Invalid value of type {typ} received as the include_mathjax argument Received value: {val} include_mathjax may be specified as False, 'cdn', or a string ending with '.js' """.format(typ=type(include_mathjax), val=repr(include_mathjax))) plotly_html_div = """\ <div>\ {mathjax_script}\ {load_plotlyjs}\ {load_fflatejs}\ <div id="{id}" class="plotly-graph-div" \ style="height:{height}; width:{width};"></div>\ <script type="text/javascript">\ {require_start}\ window.PLOTLYENV=window.PLOTLYENV || {{}};{base_url_line}\ {script};\ {require_end}\ </script>\ </div>""".format( mathjax_script=mathjax_script, load_plotlyjs=load_plotlyjs, load_fflatejs=load_fflatejs, id=plotdivid, width=div_width, height=div_height, base_url_line=base_url_line, require_start=require_start, script=script, require_end=require_end, ).strip() if full_html: return """\ <html> <head><meta charset="utf-8" /></head> <body> {div} </body> </html>""".format(div=plotly_html_div) else: return plotly_html_div
def to_html(fig, config=None, auto_play=True, include_plotlyjs=True, include_mathjax=False, post_script=None, full_html=True, animation_opts=None, default_width='100%', default_height='100%', validate=True): """ Convert a figure to an HTML string representation. Parameters ---------- fig: Figure object or dict representing a figure config: dict or None (default None) Plotly.js figure config options auto_play: bool (default=True) Whether to automatically start the animation sequence on page load if the figure contains frames. Has no effect if the figure does not contain frames. include_plotlyjs: bool or string (default True) Specifies how the plotly.js library is included/loaded in the output div string. If True, a script tag containing the plotly.js source code (~3MB) is included in the output. HTML files generated with this option are fully self-contained and can be used offline. If 'cdn', a script tag that references the plotly.js CDN is included in the output. HTML files generated with this option are about 3MB smaller than those generated with include_plotlyjs=True, but they require an active internet connection in order to load the plotly.js library. If 'directory', a script tag is included that references an external plotly.min.js bundle that is assumed to reside in the same directory as the HTML file. If 'require', Plotly.js is loaded using require.js. This option assumes that require.js is globally available and that it has been globally configured to know how to find Plotly.js as 'plotly'. This option is not advised when full_html=True as it will result in a non-functional html file. If a string that ends in '.js', a script tag is included that references the specified path. This approach can be used to point the resulting HTML file to an alternative CDN or local bundle. If False, no script tag referencing plotly.js is included. This is useful when the resulting div string will be placed inside an HTML document that already loads plotly.js. This option is not advised when full_html=True as it will result in a non-functional html file. include_mathjax: bool or string (default False) Specifies how the MathJax.js library is included in the output html div string. MathJax is required in order to display labels with LaTeX typesetting. If False, no script tag referencing MathJax.js will be included in the output. If 'cdn', a script tag that references a MathJax CDN location will be included in the output. HTML div strings generated with this option will be able to display LaTeX typesetting as long as internet access is available. If a string that ends in '.js', a script tag is included that references the specified path. This approach can be used to point the resulting HTML div string to an alternative CDN. post_script: str or list or None (default None) JavaScript snippet(s) to be included in the resulting div just after plot creation. The string(s) may include '{plot_id}' placeholders that will then be replaced by the `id` of the div element that the plotly.js figure is associated with. One application for this script is to install custom plotly.js event handlers. full_html: bool (default True) If True, produce a string containing a complete HTML document starting with an <html> tag. If False, produce a string containing a single <div> element. animation_opts: dict or None (default None) dict of custom animation parameters to be passed to the function Plotly.animate in Plotly.js. See https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js for available options. Has no effect if the figure does not contain frames, or auto_play is False. default_width, default_height: number or str (default '100%') The default figure width/height to use if the provided figure does not specify its own layout.width/layout.height property. May be specified in pixels as an integer (e.g. 500), or as a css width style string (e.g. '500px', '100%'). validate: bool (default True) True if the figure should be validated before being converted to JSON, False otherwise. Returns ------- str Representation of figure as an HTML div string """ # ## Validate figure ## fig_dict = validate_coerce_fig_to_dict(fig, validate) # ## Generate div id ## plotdivid = str(uuid.uuid4()) # ## Serialize figure ## jdata = json.dumps( fig_dict.get('data', []), cls=utils.PlotlyJSONEncoder, sort_keys=True) jlayout = json.dumps( fig_dict.get('layout', {}), cls=utils.PlotlyJSONEncoder, sort_keys=True) if fig_dict.get('frames', None): jframes = json.dumps( fig_dict.get('frames', []), cls=utils.PlotlyJSONEncoder) else: jframes = None # ## Serialize figure config ## config = _get_jconfig(config) # Set responsive config.setdefault('responsive', True) jconfig = json.dumps(config) # Get div width/height layout_dict = fig_dict.get('layout', {}) template_dict = (fig_dict .get('layout', {}) .get('template', {}) .get('layout', {})) div_width = layout_dict.get( 'width', template_dict.get('width', default_width)) div_height = layout_dict.get( 'height', template_dict.get('height', default_height)) # Add 'px' suffix to numeric widths try: float(div_width) except (ValueError, TypeError): pass else: div_width = str(div_width) + 'px' try: float(div_height) except (ValueError, TypeError): pass else: div_height = str(div_height) + 'px' # ## Get platform URL ## plotly_platform_url = config.get('plotlyServerURL', 'https://plot.ly') # ## Build script body ## # This is the part that actually calls Plotly.js # build post script snippet(s) then_post_script = '' if post_script: if not isinstance(post_script, (list, tuple)): post_script = [post_script] for ps in post_script: then_post_script += """.then(function(){{ {post_script} }})""".format( post_script=ps.replace('{plot_id}', plotdivid)) then_addframes = '' then_animate = '' if jframes: then_addframes = """.then(function(){{ Plotly.addFrames('{id}', {frames}); }})""".format(id=plotdivid, frames=jframes) if auto_play: if animation_opts: animation_opts_arg = ', ' + json.dumps(animation_opts) else: animation_opts_arg = '' then_animate = """.then(function(){{ Plotly.animate('{id}', null{animation_opts}); }})""".format(id=plotdivid, animation_opts=animation_opts_arg) script = """ if (document.getElementById("{id}")) {{ Plotly.newPlot( '{id}', {data}, {layout}, {config} ){then_addframes}{then_animate}{then_post_script} }}""".format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig, then_addframes=then_addframes, then_animate=then_animate, then_post_script=then_post_script) # ## Handle loading/initializing plotly.js ## include_plotlyjs_orig = include_plotlyjs if isinstance(include_plotlyjs, six.string_types): include_plotlyjs = include_plotlyjs.lower() # Start/end of requirejs block (if any) require_start = '' require_end = '' # Init and load load_plotlyjs = '' # Init plotlyjs. This block needs to run before plotly.js is loaded in # order for MathJax configuration to work properly if include_plotlyjs == 'require': require_start = 'require(["plotly"], function(Plotly) {' require_end = '});' elif include_plotlyjs == 'cdn': load_plotlyjs = """\ {win_config} <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>\ """.format(win_config=_window_plotly_config) elif include_plotlyjs == 'directory': load_plotlyjs = """\ {win_config} <script src="plotly.min.js"></script>\ """.format(win_config=_window_plotly_config) elif (isinstance(include_plotlyjs, six.string_types) and include_plotlyjs.endswith('.js')): load_plotlyjs = """\ {win_config} <script src="{url}"></script>\ """.format(win_config=_window_plotly_config, url=include_plotlyjs_orig) elif include_plotlyjs: load_plotlyjs = """\ {win_config} <script type="text/javascript">{plotlyjs}</script>\ """.format(win_config=_window_plotly_config, plotlyjs=get_plotlyjs()) # ## Handle loading/initializing MathJax ## include_mathjax_orig = include_mathjax if isinstance(include_mathjax, six.string_types): include_mathjax = include_mathjax.lower() mathjax_template = """\ <script src="{url}?config=TeX-AMS-MML_SVG"></script>""" if include_mathjax == 'cdn': mathjax_script = mathjax_template.format( url=('https://cdnjs.cloudflare.com' '/ajax/libs/mathjax/2.7.5/MathJax.js')) + _mathjax_config elif (isinstance(include_mathjax, six.string_types) and include_mathjax.endswith('.js')): mathjax_script = mathjax_template.format( url=include_mathjax_orig) + _mathjax_config elif not include_mathjax: mathjax_script = '' else: raise ValueError("""\ Invalid value of type {typ} received as the include_mathjax argument Received value: {val} include_mathjax may be specified as False, 'cdn', or a string ending with '.js' """.format(typ=type(include_mathjax), val=repr(include_mathjax))) plotly_html_div = """\ <div> {mathjax_script} {load_plotlyjs} <div id="{id}" class="plotly-graph-div" \ style="height:{height}; width:{width};"></div> <script type="text/javascript"> {require_start} window.PLOTLYENV=window.PLOTLYENV || {{}}; window.PLOTLYENV.BASE_URL='{plotly_platform_url}'; {script}; {require_end} </script> </div>""".format( mathjax_script=mathjax_script, load_plotlyjs=load_plotlyjs, id=plotdivid, width=div_width, height=div_height, plotly_platform_url=plotly_platform_url, require_start=require_start, script=script, require_end=require_end) if full_html: return """\ <html> <head><meta charset="utf-8" /></head> <body> {div} </body> </html>""".format(div=plotly_html_div) else: return plotly_html_div