def new_plot(self, figure_or_data, validate=True, on_completion=None, delay=0): """ See https://plot.ly/javascript/plotlyjs-function-reference/ Note that JS functions are in camelCase. The only difference is that you need to pass a figure if you want to specify a layout. Note: newPlot unregisters all your event handlers. """ on_completion_id = None if on_completion: on_completion_id = str(uuid.uuid4()) self._uid_dict[on_completion_id] = on_completion figure = tools.return_figure_from_figure_or_data( figure_or_data, validate) message = { 'method': 'newPlot', 'data': figure.get('data', []), 'layout': figure.get('layout', {}), 'graphId': self._graph_id, 'delay': delay, 'on_completion_id': on_completion_id, } self._send_message(message) # newPlot unregisters all the event handlers. self._event_handlers.clear()
def render(self, fig_dict): """Called by plotly.io.show""" stack = inspect.stack() # Name of .py example script from which plot function was called try: filename = stack[3].filename # let's hope this is robust... except (IndexError, AttributeError): # python 2 filename = stack[3][1] # NB: this works for multiple plots in the same file # It appears they are executed sequentially filename_root, _ = os.path.splitext(filename) filename_html = filename_root + ".html" filename_png = filename_root + ".png" _ = write_html(fig_dict, file=filename_html) # Whether to render the html image as a png for the thumbnail render_png = False if render_png: # Requires plotly-orca and xfvb # https://github.com/plotly/orca plotly.io.orca.config.use_xvfb = True figure = return_figure_from_figure_or_data(fig_dict, True) write_image(figure, filename_png) else: # The thumbnail isn't important, so we use a default image # Assumes the default image is one level above the .py file filename_default_image = Path(filename_root).parents[1].joinpath('default_thumb.png') shutil.copyfile(filename_default_image, filename_png)
def plot_to_div(figure_or_data, plotdivid='', added_js='', default_width='100%', default_height='100%'): """ Generate the Plotly plot, and return the HTML and Javascript needed to generate the plot. :param figure_or_data: dict :param plotdivid: string :param added_js: bool :param default_width: string :param default_height: string :return: tuple """ figure = tools.return_figure_from_figure_or_data(figure_or_data, validate_figure=True) width = figure.get('layout', {}).get('width', default_width) height = figure.get('layout', {}).get('height', default_height) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(height) except (ValueError, TypeError): pass else: height = str(height) + 'px' jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = True config['linkText'] = "View on plot.ly" jconfig = json.dumps(config) plotly_platform_url = 'https://plot.ly' script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig) plotly_html_div = ( '' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '').format( id=plotdivid, height=height, width=width) plotly_script = ( '' 'window.PLOTLYENV=window.PLOTLYENV || {{}};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '{script};{added_js}').format(script=script, added_js=added_js) return plotly_html_div, plotly_script
def new_iplot(figure_or_data, show_link=True, link_text='Export to plot.ly',validate=True): figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', 525) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text jconfig = json.dumps(config) plotly_platform_url = session.get_session_config().get('plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url .replace('https://', '') .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) script = '\n'.join([ 'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{', ' $(".{id}.loading").remove();', '}})' ]).format(id=plotdivid, data=jdata, layout=jlayout, config=jconfig) html="""<div class="{id} loading" style="color: rgb(50,50,50);"> </div> <div id="{id}" style="height: {height}; width: {width};" class="plotly-graph-div"> </div> <script type="text/javascript"> {script} </script> """.format(id=plotdivid, script=script, height=height, width=width) return html
def _plot_html(figure_or_data, show_link, link_text, validate, default_width, default_height): figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', default_width) height = figure.get('layout', {}).get('height', default_height) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text jconfig = json.dumps(config) # TODO: The get_config 'source of truth' should # really be somewhere other than plotly.plotly plotly_platform_url = plotly.plotly.get_config().get( 'plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig) plotly_html_div = ( '' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' 'window.PLOTLYENV=window.PLOTLYENV || {{}};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '{script}' '</script>' '').format(id=plotdivid, script=script, height=height, width=width) return plotly_html_div, plotdivid, width, height
def _plot_html(figure_or_data, show_link, link_text, validate, default_width, default_height): figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get("layout", {}).get("width", default_width) height = figure.get("layout", {}).get("height", default_height) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + "px" try: float(width) except (ValueError, TypeError): pass else: width = str(width) + "px" plotdivid = uuid.uuid4() jdata = json.dumps(figure.get("data", []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get("layout", {}), cls=utils.PlotlyJSONEncoder) config = {} config["showLink"] = show_link config["linkText"] = link_text jconfig = json.dumps(config) # TODO: The get_config 'source of truth' should # really be somewhere other than plotly.plotly plotly_platform_url = plotly.plotly.get_config().get("plotly_domain", "https://plot.ly") if plotly_platform_url != "https://plot.ly" and link_text == "Export to plot.ly": link_domain = plotly_platform_url.replace("https://", "").replace("http://", "") link_text = link_text.replace("plot.ly", link_domain) script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig ) plotly_html_div = ( "" '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' "</div>" '<script type="text/javascript">' "window.PLOTLYENV=window.PLOTLYENV || {{}};" 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' "{script}" "</script>" "" ).format(id=plotdivid, script=script, height=height, width=width) return plotly_html_div, plotdivid, width, height
def plot(self, figure_or_data, validate=True): """Plot figure_or_data in the Plotly graph widget. Args: figure_or_data (dict, list, or plotly.graph_obj object): The standard Plotly graph object that describes Plotly graphs as used in `plotly.plotly.plot`. See examples of the figure_or_data in https://plot.ly/python/ Returns: None Example 1 - Graph a scatter plot: ``` from plotly.graph_objs import Scatter g = GraphWidget() g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])]) ``` Example 2 - Graph a scatter plot with a title: ``` from plotly.graph_objs import Scatter, Figure, Data fig = Figure( data = Data([ Scatter(x=[1, 2, 3], y=[20, 15, 13]) ]), layout = Layout(title='Experimental Data') ) g = GraphWidget() g.plot(fig) ``` Example 3 - Clear a graph widget ``` from plotly.graph_objs import Scatter, Figure g = GraphWidget() g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])]) # Now clear it g.plot({}) # alternatively, g.plot(Figure()) ``` """ if figure_or_data == {} or figure_or_data == Figure(): validate = False figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) message = { 'task': 'newPlot', 'data': figure.get('data', []), 'layout': figure.get('layout', {}), 'graphId': self._graphId } self._handle_outgoing_message(message)
def plot(self, figure_or_data, validate=True): """Plot figure_or_data in the Plotly graph widget. Args: figure_or_data (dict, list, or plotly.graph_obj object): The standard Plotly graph object that describes Plotly graphs as used in `plotly.plotly.plot`. See examples of the figure_or_data in https://plot.ly/python/ Returns: None Example 1 - Graph a scatter plot: ``` from plotly.graph_objs import Scatter g = GraphWidget() g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])]) ``` Example 2 - Graph a scatter plot with a title: ``` from plotly.graph_objs import Scatter, Figure, Data fig = Figure( data = Data([ Scatter(x=[1, 2, 3], y=[20, 15, 13]) ]), layout = Layout(title='Experimental Data') ) g = GraphWidget() g.plot(fig) ``` Example 3 - Clear a graph widget ``` from plotly.graph_objs import Scatter, Figure g = GraphWidget() g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])]) # Now clear it g.plot({}) # alternatively, g.plot(Figure()) ``` """ if figure_or_data == {} or figure_or_data == Figure(): validate = False figure = tools.return_figure_from_figure_or_data( figure_or_data, validate) message = { 'task': 'newPlot', 'data': figure.get('data', []), 'layout': figure.get('layout', {}), 'graphId': self._graphId } self._handle_outgoing_message(message)
def render(self, fig_dict): stack = inspect.stack() # Name of script from which plot function was called is retrieved try: filename = stack[3].filename # let's hope this is robust... except: # python 2 filename = stack[3][1] filename_root, _ = os.path.splitext(filename) filename_html = filename_root + ".html" filename_png = filename_root + ".png" figure = return_figure_from_figure_or_data(fig_dict, True) _ = write_html(fig_dict, file=filename_html) write_image(figure, filename_png)
def test_plot_url_given_sharing_key(self): # Give share_key is requested, the retun url should contain # the share_key validate = True fig = tls.return_figure_from_figure_or_data(self.simple_figure, validate) kwargs = {'filename': 'is_share_key_included', 'fileopt': 'overwrite', 'world_readable': False, 'sharing': 'secret'} response = py._send_to_plotly(fig, **kwargs) plot_url = response['url'] self.assertTrue('share_key=' in plot_url)
def plot(figure_or_data, validate=True, **plot_options): """Create a unique url for this plot in Plotly and optionally open url. plot_options keyword agruments: filename (string) -- the name that will be associated with this figure fileopt ('new' | 'overwrite' | 'extend' | 'append') -- 'new' creates a 'new': create a new, unique url for this plot 'overwrite': overwrite the file associated with `filename` with this 'extend': add additional numbers (data) to existing traces 'append': add additional traces to existing data lists world_readable (default=True) -- make this figure private/public auto_open (default=True) -- Toggle browser options True: open this plot in a new browser tab False: do not open plot in the browser, but do return the unique url """ figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) for entry in figure['data']: for key, val in list(entry.items()): try: if len(val) > 40000: msg = ("Woah there! Look at all those points! Due to " "browser limitations, Plotly has a hard time " "graphing more than 500k data points for line " "charts, or 40k points for other types of charts. " "Here are some suggestions:\n" "(1) Trying using the image API to return an image " "instead of a graph URL\n" "(2) Use matplotlib\n" "(3) See if you can create your visualization with " "fewer data points\n\n" "If the visualization you're using aggregates " "points (e.g., box plot, histogram, etc.) you can " "disregard this warning.") warnings.warn(msg) except TypeError: pass plot_options = _plot_option_logic(plot_options) res = _send_to_plotly(figure, **plot_options) if res['error'] == '': if plot_options['auto_open']: _open_url(res['url']) return res['url'] else: raise exceptions.PlotlyAccountError(res['error'])
def render(self, fig_dict): stack = inspect.stack() # Name of script from which plot function was called is retrieved try: filename = stack[3].filename # let's hope this is robust... except: # python 2 filename = stack[3][1] filename_root, _ = os.path.splitext(filename) filename_html = filename_root + ".html" filename_png = filename_root + ".png" figure = return_figure_from_figure_or_data(fig_dict, True) _ = write_html(fig_dict, file=filename_html, include_plotlyjs="cdn") try: write_image(figure, filename_png) except (ValueError, ImportError): raise ImportError( "orca and psutil are required to use the `sphinx-gallery-orca` renderer. " "See https://plotly.com/python/static-image-export/ for instructions on" "how to install orca. Alternatively, you can use the `sphinx-gallery`" "renderer (note that png thumbnails can only be generated with" "the `sphinx-gallery-orca` renderer).")
def new_iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True): figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', 525) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text jconfig = json.dumps(config) plotly_platform_url = session.get_session_config().get( 'plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) script = '\n'.join([ 'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{', ' $(".{id}.loading").remove();', '}})' ]).format(id=plotdivid, data=jdata, layout=jlayout, config=jconfig) html = """<div class="{id} loading" style="color: rgb(50,50,50);"> Drawing...</div> <div id="{id}" style="height: {height}; width: {width};" class="plotly-graph-div"> </div> <script type="text/javascript"> {script} </script> """.format(id=plotdivid, script=script, height=height, width=width) return html
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600, config=None): """ Draw plotly graphs inside an IPython or Jupyter notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js 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. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) # We can also download an image of the plot by setting the image to the format you want. e.g. `image='png'` iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png') ``` """ if not ipython: raise ImportError('`iplot` can only run inside an IPython Notebook.') config = dict(config) if config else {} config.setdefault('showLink', show_link) config.setdefault('linkText', link_text) 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} 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 ) display_bundle['text/html'] = plot_html display_bundle['text/vnd.plotly.v1+html'] = plot_html 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))
def _plot_html(figure_or_data, config, validate, default_width, default_height, global_requirejs): # force no validation if frames is in the call # TODO - add validation for frames in call - #605 if 'frames' in figure_or_data: figure = tools.return_figure_from_figure_or_data( figure_or_data, False ) else: figure = tools.return_figure_from_figure_or_data( figure_or_data, validate ) width = figure.get('layout', {}).get('width', default_width) height = figure.get('layout', {}).get('height', default_height) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(height) except (ValueError, TypeError): pass else: height = str(height) + 'px' plotdivid = uuid.uuid4() jdata = _json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = _json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) if 'frames' in figure_or_data: jframes = _json.dumps(figure.get('frames', {}), cls=utils.PlotlyJSONEncoder) configkeys = ( 'editable', 'autosizable', 'fillFrame', 'frameMargins', 'scrollZoom', 'doubleClick', 'showTips', 'showLink', 'sendData', 'linkText', 'showSources', 'displayModeBar', 'modeBarButtonsToRemove', 'modeBarButtonsToAdd', 'modeBarButtons', 'displaylogo', 'plotGlPixelRatio', 'setBackground', 'topojsonURL' ) config_clean = dict((k, config[k]) for k in configkeys if k in config) jconfig = _json.dumps(config_clean) # TODO: The get_config 'source of truth' should # really be somewhere other than plotly.plotly plotly_platform_url = plotly.plotly.get_config().get('plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and config['linkText'] == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = config['linkText'].replace('plot.ly', link_domain) config['linkText'] = link_text jconfig = jconfig.replace('Export to plot.ly', link_text) if 'frames' in figure_or_data: script = ''' Plotly.plot( '{id}', {data}, {layout}, {config} ).then(function () {add_frames}).then(function(){animate}) '''.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig, add_frames="{" + "return Plotly.addFrames('{id}',{frames}".format( id=plotdivid, frames=jframes ) + ");}", animate="{" + "Plotly.animate('{id}');".format(id=plotdivid) + "}" ) else: script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig) optional_line1 = ('require(["plotly"], function(Plotly) {{ ' if global_requirejs else '') optional_line2 = ('}});' if global_requirejs else '') plotly_html_div = ( '' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' + optional_line1 + 'window.PLOTLYENV=window.PLOTLYENV || {{}};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '{script}' + optional_line2 + '</script>' '').format( id=plotdivid, script=script, height=height, width=width) return plotly_html_div, plotdivid, width, height
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600, config=None): """ Draw plotly graphs inside an IPython or Jupyter notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js 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. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) # We can also download an image of the plot by setting the image to the format you want. e.g. `image='png'` iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png') ``` """ 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 not ipython: raise ImportError('`iplot` can only run inside an IPython Notebook.') config = dict(config) if config else {} config.setdefault('showLink', show_link) config.setdefault('linkText', link_text) plot_html, plotdivid, width, height = _plot_html( figure_or_data, config, validate, '100%', 525, True ) 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} if frames: fig['frames'] = frames display_bundle = { 'application/vnd.plotly.v1+json': fig, 'text/html': plot_html, 'text/vnd.plotly.v1+html': plot_html } ipython_display.display(display_bundle, raw=True) if image: 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))
def iplot(figure_or_data, show_link=False, link_text='', validate=True): """ Draw plotly graphs inside a Zeppelin notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) ``` """ figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', 525) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text config['displayModeBar'] = False jconfig = json.dumps(config) script = '\n'.join([ 'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{', ' $(".{id}.loading").remove();', '}})' ]).format(id=plotdivid, data=jdata, layout=jlayout, config=jconfig) print("""%html <div class="{id} loading" style="color: rgb(50,50,50);"> Drawing...</div> <div id="{id}" style="height: {height}; width: {width};" class="plotly-graph-div"> </div> <script type="text/javascript"> {script} </script> """.format(id=plotdivid, script=script, height=height, width=width))
def plot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, output_type='file', include_plotlyjs=True, filename='temp-plot.html', auto_open=True): """ Create a plotly graph locally as an HTML document or string. Example: ``` from plotly.offline import plot import plotly.graph_objs as go plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html') ``` More examples below. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. output_type ('file' | 'div' - default 'file') -- if 'file', then the graph is saved as a standalone HTML file and `plot` returns None. If 'div', then `plot` returns a string that just contains the HTML <div> that contains the graph and the script to generate the graph. Use 'file' if you want to save and view a single graph at a time in a standalone HTML file. Use 'div' if you are embedding these graphs in an HTML file with other graphs or HTML markup, like a HTML report or an website. include_plotlyjs (default=True) -- If True, include the plotly.js source code in the output file or string. Set as False if your HTML file already contains a copy of the plotly.js library. filename (default='temp-plot.html') -- The local filename to save the outputted chart to. If the filename already exists, it will be overwritten. This argument only applies if `output_type` is 'file'. auto_open (default=True) -- If True, open the saved file in a web browser after saving. This argument only applies if `output_type` is 'file'. """ if output_type not in ['div', 'file']: raise ValueError("`output_type` argument must be 'div' or 'file'. " "You supplied `" + output_type + "``") if not filename.endswith('.html') and output_type == 'file': warnings.warn("Your filename `" + filename + "` didn't end with .html. " "Adding .html to the end of your file.") filename += '.html' plot_html, plotdivid, width, height = _plot_html(figure_or_data, show_link, link_text, validate, '100%', '100%') figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) resize_script = '' if width == '100%' or height == '100%': resize_script = ( '' '<script type="text/javascript">' 'window.removeEventListener("resize");' 'window.addEventListener("resize", function(){{' 'Plotly.Plots.resize(document.getElementById("{id}"));}});' '</script>').format(id=plotdivid) if output_type == 'file': with open(filename, 'w') as f: if include_plotlyjs: plotly_js_script = ''.join([ '<script type="text/javascript">', get_plotlyjs(), '</script>', ]) else: plotly_js_script = '' f.write(''.join([ '<html>', '<head><meta charset="utf-8" /></head>', '<body>', plotly_js_script, plot_html, resize_script, '</body>', '</html>' ])) url = 'file://' + os.path.abspath(filename) if auto_open: webbrowser.open(url) return url elif output_type == 'div': if include_plotlyjs: return ''.join([ '<div>', '<script type="text/javascript">', get_plotlyjs(), '</script>', plot_html, '</div>' ]) else: return plot_html
def plot(figure_or_data, show_link=False, link_text='Export to plot.ly', validate=True, output_type='file', include_plotlyjs=True, filename='temp-plot.html', auto_open=True, image=None, image_filename='plot_image', image_width=800, image_height=600, config=None, include_mathjax=False, auto_play=True, animation_opts=None): """ Create a plotly graph locally as an HTML document or string. Example: ``` from plotly.offline import plot import plotly.graph_objs as go plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html') # We can also download an image of the plot by setting the image parameter # to the image format we want plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html', image='jpeg') ``` More examples below. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=False) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. output_type ('file' | 'div' - default 'file') -- if 'file', then the graph is saved as a standalone HTML file and `plot` returns None. If 'div', then `plot` returns a string that just contains the HTML <div> that contains the graph and the script to generate the graph. Use 'file' if you want to save and view a single graph at a time in a standalone HTML file. Use 'div' if you are embedding these graphs in an HTML file with other graphs or HTML markup, like a HTML report or an website. include_plotlyjs (True | False | 'cdn' | 'directory' | path - default=True) Specifies how the plotly.js library is included in the output html file or 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 output_type='file' then the plotly.min.js bundle is copied into the directory of the resulting HTML file. If a file named plotly.min.js already exists in the output directory then this file is left unmodified and no copy is performed. HTML files generated with this option can be used offline, but they require a copy of the plotly.min.js bundle in the same directory. This option is useful when many figures will be saved as HTML files in the same directory because the plotly.js source code will be included only once per output directory, rather than once per output 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. If False, no script tag referencing plotly.js is included. This is useful when output_type='div' and the resulting div string will be placed inside an HTML document that already loads plotly.js. This option is not advised when output_type='file' as it will result in a non-functional html file. filename (default='temp-plot.html') -- The local filename to save the outputted chart to. If the filename already exists, it will be overwritten. This argument only applies if `output_type` is 'file'. auto_open (default=True) -- If True, open the saved file in a web browser after saving. This argument only applies if `output_type` is 'file'. 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. image_filename (default='plot_image') -- 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. include_mathjax (False | 'cdn' | path - default=False) -- Specifies how the MathJax.js library is included in the output html file or 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. HTML files generated with this option will not be able to display LaTeX typesetting. If 'cdn', a script tag that references a MathJax CDN location will be included in the output. HTML files generated with this option will be able to display LaTeX typesetting as long as they have internet access. 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. auto_play (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. animation_opts (default=None) -- Dict of custom animation parameters that are used for the automatically started animation on page load. This dict is 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. Example: ``` from plotly.offline import plot figure = {'data': [{'x': [0, 1], 'y': [0, 1]}], 'layout': {'xaxis': {'range': [0, 5], 'autorange': False}, 'yaxis': {'range': [0, 5], 'autorange': False}, 'title': 'Start Title'}, 'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]}, {'data': [{'x': [1, 4], 'y': [1, 4]}]}, {'data': [{'x': [3, 4], 'y': [3, 4]}], 'layout': {'title': 'End Title'}}]} iplot(figure, animation_opts={'frame': {'duration': 1}}) ``` """ import plotly.io as pio # Output type if output_type not in ['div', 'file']: raise ValueError( "`output_type` argument must be 'div' or 'file'. " "You supplied `" + output_type + "``") if not filename.endswith('.html') and output_type == 'file': warnings.warn( "Your filename `" + filename + "` didn't end with .html. " "Adding .html to the end of your file.") filename += '.html' # Config config = dict(config) if config else {} config.setdefault('showLink', show_link) config.setdefault('linkText', link_text) figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', '100%') if width == '100%' or height == '100%': config.setdefault('responsive', True) # Handle image request post_script = build_save_image_post_script( image, image_filename, image_height, image_width, 'plot') if output_type == 'file': pio.write_html( figure, filename, config=config, auto_play=auto_play, include_plotlyjs=include_plotlyjs, include_mathjax=include_mathjax, post_script=post_script, full_html=True, validate=validate, animation_opts=animation_opts, auto_open=auto_open) return filename else: return pio.to_html( figure, config=config, auto_play=auto_play, include_plotlyjs=include_plotlyjs, include_mathjax=include_mathjax, post_script=post_script, full_html=False, validate=validate, animation_opts=animation_opts)
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True): """ Draw plotly graphs inside an IPython notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) ``` """ 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 not tools._ipython_imported: raise ImportError('`iplot` can only run inside an IPython Notebook.') from IPython.display import HTML, display figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', 525) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text jconfig = json.dumps(config) # TODO: The get_config 'source of truth' should # really be somewhere other than plotly.plotly plotly_platform_url = plotly.plotly.get_config().get('plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) display(HTML( '<script type="text/javascript">' 'window.PLOTLYENV=window.PLOTLYENV || {};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '</script>' )) script = '\n'.join([ 'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{', ' $(".{id}.loading").remove();', '}})' ]).format(id=plotdivid, data=jdata, layout=jlayout, config=jconfig) display(HTML('' '<div class="{id} loading" style="color: rgb(50,50,50);">' 'Drawing...</div>' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' '{script}' '</script>' ''.format(id=plotdivid, script=script, height=height, width=width)))
def setup_figure(data, datetimes, use_gradient, show_yaxis_ticks, height): """Create figure.""" n_channels = data.shape[1] datetimes = [ dt.utcfromtimestamp((datetime + np.timedelta64(3, 'h')).tolist() / 1e9) for datetime in datetimes ] domains = np.linspace(1, 0, n_channels + 1) # fig = tools.make_subplots( # rows=n_channels, # cols=1, # # specs=[[{}]] * n_channels, # shared_xaxes=True, # shared_yaxes=True, # vertical_spacing=-5, # print_grid=False # ) traces = create_traces(data, datetimes, n_channels, use_gradient) # for i, trace in tqdm(enumerate(traces), desc='Appending traces to figure'): # fig.append_trace(trace, i + 1, 1) # for i, trace in tqdm(enumerate(traces), desc='Updating layout'): # fig['layout'].update({ # f'yaxis{i + 1}': YAxis({ # 'domain': np.flip(domains[i:i + 2], axis=0), # 'showticklabels': show_yaxis_ticks, # 'zeroline': False, # 'showgrid': False, # 'automargin': False # }), # 'showlegend': False, # 'margin': {'t': 0, 'l': 0} # }) layout = Layout(**{ f'yaxis{i + 1}': YAxis({ 'domain': np.flip(domains[i:i + 2], axis=0), 'showticklabels': show_yaxis_ticks, 'zeroline': False, 'showgrid': False, 'automargin': False }) for i in range(len(traces)) }, showlegend=False, autosize=False, height=height, margin={ 't': 0, 'l': 0 }) logger.info("Appending traces") fig = tools.return_figure_from_figure_or_data( { 'data': traces, 'layout': layout }, validate_figure=False) # fig = Figure(data=traces, layout=layout) # if not show_yaxis_ticks: annotations = create_annotations(data, n_channels) fig['layout'].update(annotations=annotations) # # fig['layout'].update(autosize=False, height=height) fig['layout']['xaxis'].update(side='top') fig['layout']['xaxis'].update(tickformat='%H:%M:%S:%L') fig['layout']['xaxis'].update(mirror='allticks', side='bottom') logger.info("Figure set up") return fig
def plot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, output_type='file', include_plotlyjs=True, filename='temp-plot.html', auto_open=True): """ Create a plotly graph locally as an HTML document or string. Example: ``` from plotly.offline import plot import plotly.graph_objs as go plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html') ``` More examples below. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. output_type ('file' | 'div' - default 'file') -- if 'file', then the graph is saved as a standalone HTML file and `plot` returns None. If 'div', then `plot` returns a string that just contains the HTML <div> that contains the graph and the script to generate the graph. Use 'file' if you want to save and view a single graph at a time in a standalone HTML file. Use 'div' if you are embedding these graphs in an HTML file with other graphs or HTML markup, like a HTML report or an website. include_plotlyjs (default=True) -- If True, include the plotly.js source code in the output file or string. Set as False if your HTML file already contains a copy of the plotly.js library. filename (default='temp-plot.html') -- The local filename to save the outputted chart to. If the filename already exists, it will be overwritten. This argument only applies if `output_type` is 'file'. auto_open (default=True) -- If True, open the saved file in a web browser after saving. This argument only applies if `output_type` is 'file'. """ if output_type not in ['div', 'file']: raise ValueError( "`output_type` argument must be 'div' or 'file'. " "You supplied `" + output_type + "``") if not filename.endswith('.html') and output_type == 'file': warnings.warn( "Your filename `" + filename + "` didn't end with .html. " "Adding .html to the end of your file.") filename += '.html' plot_html, plotdivid, width, height = _plot_html( figure_or_data, show_link, link_text, validate, '100%', '100%') figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) resize_script = '' if width == '100%' or height == '100%': resize_script = ( '' '<script type="text/javascript">' 'window.removeEventListener("resize");' 'window.addEventListener("resize", function(){{' 'Plotly.Plots.resize(document.getElementById("{id}"));}});' '</script>' ).format(id=plotdivid) if output_type == 'file': with open(filename, 'w') as f: if include_plotlyjs: plotly_js_script = ''.join([ '<script type="text/javascript">', get_plotlyjs(), '</script>', ]) else: plotly_js_script = '' f.write(''.join([ '<html>', '<head><meta charset="utf-8" /></head>', '<body>', plotly_js_script, plot_html, resize_script, '</body>', '</html>'])) url = 'file://' + os.path.abspath(filename) if auto_open: webbrowser.open(url) return url elif output_type == 'div': if include_plotlyjs: return ''.join([ '<div>', '<script type="text/javascript">', get_plotlyjs(), '</script>', plot_html, '</div>' ]) else: return plot_html
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True): """ Draw plotly graphs inside an IPython notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) ``` """ 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 not tools._ipython_imported: raise ImportError('`iplot` can only run inside an IPython Notebook.') from IPython.display import HTML, display figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', 525) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text jconfig = json.dumps(config) plotly_platform_url = session.get_session_config().get('plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) display(HTML( '<script type="text/javascript">' 'window.PLOTLYENV=window.PLOTLYENV || {};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '</script>' )) script = '\n'.join([ 'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{', ' $(".{id}.loading").remove();', '}})' ]).format(id=plotdivid, data=jdata, layout=jlayout, config=jconfig) display(HTML('' '<div class="{id} loading" style="color: rgb(50,50,50);">' 'Drawing...</div>' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' '{script}' '</script>' ''.format(id=plotdivid, script=script, height=height, width=width)))
def plot(figure_or_data, show_link=False, link_text='Export to plot.ly', validate=True, output_type='file', include_plotlyjs=True, filename='temp-plot.html', auto_open=True, image=None, image_filename='plot_image', image_width=800, image_height=600, config=None, include_mathjax=False, auto_play=True, animation_opts=None): """ Create a plotly graph locally as an HTML document or string. Example: ``` from plotly.offline import plot import plotly.graph_objs as go plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html') # We can also download an image of the plot by setting the image parameter # to the image format we want plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html', image='jpeg') ``` More examples below. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=False) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. output_type ('file' | 'div' - default 'file') -- if 'file', then the graph is saved as a standalone HTML file and `plot` returns None. If 'div', then `plot` returns a string that just contains the HTML <div> that contains the graph and the script to generate the graph. Use 'file' if you want to save and view a single graph at a time in a standalone HTML file. Use 'div' if you are embedding these graphs in an HTML file with other graphs or HTML markup, like a HTML report or an website. include_plotlyjs (True | False | 'cdn' | 'directory' | path - default=True) Specifies how the plotly.js library is included in the output html file or 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 output_type='file' then the plotly.min.js bundle is copied into the directory of the resulting HTML file. If a file named plotly.min.js already exists in the output directory then this file is left unmodified and no copy is performed. HTML files generated with this option can be used offline, but they require a copy of the plotly.min.js bundle in the same directory. This option is useful when many figures will be saved as HTML files in the same directory because the plotly.js source code will be included only once per output directory, rather than once per output 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. If False, no script tag referencing plotly.js is included. This is useful when output_type='div' and the resulting div string will be placed inside an HTML document that already loads plotly.js. This option is not advised when output_type='file' as it will result in a non-functional html file. filename (default='temp-plot.html') -- The local filename to save the outputted chart to. If the filename already exists, it will be overwritten. This argument only applies if `output_type` is 'file'. auto_open (default=True) -- If True, open the saved file in a web browser after saving. This argument only applies if `output_type` is 'file'. 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. image_filename (default='plot_image') -- 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. include_mathjax (False | 'cdn' | path - default=False) -- Specifies how the MathJax.js library is included in the output html file or 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. HTML files generated with this option will not be able to display LaTeX typesetting. If 'cdn', a script tag that references a MathJax CDN location will be included in the output. HTML files generated with this option will be able to display LaTeX typesetting as long as they have internet access. 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. auto_play (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. animation_opts (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. Example: ``` from plotly.offline import plot figure = {'data': [{'x': [0, 1], 'y': [0, 1]}], 'layout': {'xaxis': {'range': [0, 5], 'autorange': False}, 'yaxis': {'range': [0, 5], 'autorange': False}, 'title': 'Start Title'}, 'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]}, {'data': [{'x': [1, 4], 'y': [1, 4]}]}, {'data': [{'x': [3, 4], 'y': [3, 4]}], 'layout': {'title': 'End Title'}}]} plot(figure,animation_opts="{frame: {duration: 1}}") ``` """ import plotly.io as pio # Output type if output_type not in ['div', 'file']: raise ValueError( "`output_type` argument must be 'div' or 'file'. " "You supplied `" + output_type + "``") if not filename.endswith('.html') and output_type == 'file': warnings.warn( "Your filename `" + filename + "` didn't end with .html. " "Adding .html to the end of your file.") filename += '.html' # Config config = dict(config) if config else {} config.setdefault('showLink', show_link) config.setdefault('linkText', link_text) figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', '100%') if width == '100%' or height == '100%': config.setdefault('responsive', True) # Handle image request post_script = build_save_image_post_script( image, image_filename, image_height, image_width, 'plot') if output_type == 'file': pio.write_html( figure, filename, config=config, auto_play=auto_play, include_plotlyjs=include_plotlyjs, include_mathjax=include_mathjax, post_script=post_script, full_html=True, validate=validate, animation_opts=animation_opts, auto_open=auto_open) return filename else: return pio.to_html( figure, config=config, auto_play=auto_play, include_plotlyjs=include_plotlyjs, include_mathjax=include_mathjax, post_script=post_script, full_html=False, validate=validate, animation_opts=animation_opts)
def plot_ex(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, resizable=False, lock_aspect_ratio=False, master=True, click_to_display=False, link_to=None, link_to_id=False, rel_figure_dir="figures"): """ Create a pyGSTi plotly graph locally, returning HTML & JS separately. Parameters ---------- figure_or_data : plotly.graph_objs.Figure or .Data or dict or list object that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. show_link : bool, optional display a link in the bottom-right corner of link_text : str, optional the text of export link validate : bool, optional validate that all of the keys in the figure are valid? omit if you need to include extra, unnecessary keys in your figure. resizable : bool, optional Make the plot resizable by including a "resize" event handler and any additional initialization. lock_aspect_ratio : bool, optional Whether the aspect ratio of the plot should be allowed to change when it is sized based on it's container. master : bool, optional Whether this plot represents the "master" of a group of plots, all of the others which are "slaves". The relative sizing of the master of a group will determine the relative sizing of the slaves, rather than the slave's containing element. Useful for preserving the size of the features in a group of plots that may be different overall sizes. click_to_display : bool, optional Whether the plot should be rendered immediately or whether a "click" icon should be shown instead, which must be clicked on to render the plot. link_to : None or tuple of {"pdf", "pkl"} If not-None, the types of pre-rendered/computed versions of this plot that can be assumed to be present, and therefore linked to by additional items in the hover-over menu of the plotly plot. link_to_id : str, optional The base name (without extension) of the ".pdf" or ".pkl" files that are to be linked to by menu items. For example, if `link_to` equals `("pdf",)` and `link_to_id` equals "plot1234", then a menu item linking to the file "plot1234.pdf" will be added to the renderd plot. Returns ------- dict With 'html' and 'js' keys separately specifying the HTML and javascript needed to embed the plot. """ from plotly import __version__ as _plotly_version from plotly import tools as _plotlytools #Processing to enable automatic-resizing & aspect ratio locking fig = _plotlytools.return_figure_from_figure_or_data(figure_or_data, False) orig_width = fig.get('layout', {}).get('width', None) orig_height = fig.get('layout', {}).get('height', None) if lock_aspect_ratio and orig_width and orig_height: aspect_ratio = orig_width / orig_height else: aspect_ratio = None #Remove original dimensions of plot so default of 100% is used below # (and triggers resize-script creation) if orig_width: del fig['layout']['width'] if orig_height: del fig['layout']['height'] #Special polar plot case - see below - add dummy width & height so # we can find/replace them with variables in generated javascript. if 'angularaxis' in fig['layout']: fig['layout']['width'] = 123 fig['layout']['height'] = 123 config = {} config['showLink'] = show_link config['linkText'] = link_text #Add version-dependent kwargs to _plot_html call below plotly_version = tuple(map(int, _plotly_version.split('.'))) if plotly_version < (3, 8, 0): # "old" plotly with _plot_html function from plotly.offline.offline import _plot_html kwargs = {} if plotly_version >= (3, 7, 0): # then auto_play arg exists kwargs['auto_play'] = False #Note: removing width and height from layout above causes default values to # be used (the '100%'s hardcoded below) which subsequently trigger adding a resize script. plot_html, plotdivid, _, _ = _plot_html( fig, config, validate, '100%', '100%', global_requirejs=False, # no need for global_requirejs here **kwargs) # since we now extract js and remake full script. else: from plotly.io import to_html as _to_html import uuid as _uuid plot_html = _to_html(fig, config, auto_play=False, include_plotlyjs=False, include_mathjax=False, post_script=None, full_html=False, animation_opts=None, validate=validate) assert (plot_html.startswith("<div>") and plot_html.endswith("</div>")) plot_html = plot_html[len("<div>"):-len("</div>")].strip() assert (plot_html.endswith("</script>")) id_index = plot_html.find('id="') id_index_end = plot_html.find('"', id_index + len('id="')) plotdivid = _uuid.UUID(plot_html[id_index + len('id="'):id_index_end]) if orig_width: fig['layout']['width'] = orig_width if orig_height: fig['layout']['height'] = orig_height # Separate the HTML and JS in plot_html so we can insert # initial-sizing JS between them. NOTE: this is FRAGILE and depends # on Plotly output (_plot_html) being HTML followed by JS tag = '<script type="text/javascript">' end_tag = '</script>' iTag = plot_html.index(tag) plot_js = plot_html[iTag + len(tag):-len(end_tag)].strip() plot_html = plot_html[0:iTag].strip() full_script = '' #Note: in this case, upper logic (usually in an on-ready hander of the table/plot # group creation) is responsible for triggering a "create" event on the plot div # when appropriate (see workspace.py). #Get javascript for create and (possibly) resize handlers plotly_create_js = plot_js # the ususal plotly creation javascript plotly_resize_js = None if resizable: #the ususal plotly resize javascript plotly_resize_js = ' Plotly.Plots.resize(document.getElementById("{id}"));'.format( id=plotdivid) if 'angularaxis' in fig['layout']: #Special case of polar plots: Plotly does *not* allow resizing of polar plots. # (I don't know why, and it's not documented, but in plotly.js there are explict conditions # in Plotly.relayout that short-circuit when "gd.frameworks.isPolar" is true). So, # we just re-create the plot with a different size to mimic resizing. plot_js = plot_js.replace('"width": 123', '"width": pw').replace( '"height": 123', '"height": ph') plotly_resize_js = ('var plotlydiv = $("#{id}");\n' 'plotlydiv.children(".plotly").remove();\n' 'var pw = plotlydiv.width();\n' 'var ph = plotlydiv.height();\n' '{resized}\n').format(id=plotdivid, resized=plot_js) plotly_create_js = plotly_resize_js aspect_val = aspect_ratio if aspect_ratio else "null" groupclass = "pygsti-plotgroup-master" \ if master else "pygsti-plotgroup-slave" if link_to and ('pdf' in link_to) and link_to_id: link_to_pdf_js = ( "\n" " btn = $('#{id}').find('.modebar-btn[data-title=\"Show closest data on hover\"]');\n" " btn = cloneAndReplace( btn ); //Strips all event handlers\n" " btn.attr('data-title','Download PDF');\n" " btn.click( function() {{\n" " window.open('{relfigdir}/{pdfid}.pdf');\n" " }});\n").format(id=plotdivid, pdfid=link_to_id, relfigdir=rel_figure_dir) plotly_create_js += link_to_pdf_js if link_to and ('pkl' in link_to) and link_to_id: link_to_pkl_js = ( "\n" " btn = $('#{id}').find('.modebar-btn[data-title=\"Zoom\"]');\n" " btn = cloneAndReplace( btn ); //Strips all event handlers\n" " btn.attr('data-title','Download python pickle');\n" " btn.click( function() {{\n" " window.open('{relfigdir}/{pklid}.pkl');\n" " }});\n").format(id=plotdivid, pklid=link_to_id, relfigdir=rel_figure_dir) plotly_create_js += link_to_pkl_js plotly_click_js = "" if click_to_display and master: # move plotly plot creation from "create" to "click" handler plotly_click_js = plotly_create_js plotly_create_js = "" full_script = ( # (assume this will all be run within an on-ready handler) ' $("#{id}").addClass("{groupclass}");\n' # perform this right away ' $("#{id}").on("init", function(event) {{\n' # always add init-size handler ' pex_init_plotdiv($("#{id}"), {ow}, {oh});\n' ' pex_init_slaves($("#{id}"));\n' ' console.log("Initialized {id}");\n' ' }});\n' ' $("#{id}").on("click.pygsti", function(event) {{\n' ' plotman.enqueue(function() {{ \n' ' {plotlyClickJS} \n' ' }}, "Click-creating Plot {id}" );\n' ' $("#{id}").off("click.pygsti");\n' # remove this event handler ' console.log("Click-Created {id}");\n' ' }});\n' ' $("#{id}").on("create", function(event, fracw, frach) {{\n' # always add create handler ' pex_update_plotdiv_size($("#{id}"), {ratio}, fracw, frach, {ow}, {oh});\n' ' plotman.enqueue(function() {{ \n' ' $("#{id}").addClass("pygBackground");\n' ' {plotlyCreateJS} \n' ' pex_create_slaves($("#{id}"), {ow}, {oh});\n' ' }}, "Creating Plot {id}" );\n' ' console.log("Created {id}");\n' ' }});\n').format(id=plotdivid, ratio=aspect_val, groupclass=groupclass, ow=orig_width if orig_width else "null", oh=orig_height if orig_height else "null", plotlyClickJS=plotly_click_js, plotlyCreateJS=plotly_create_js) #Add resize handler if needed if resizable: full_script += ( ' $("#{id}").on("resize", function(event,fracw,frach) {{\n' ' pex_update_plotdiv_size($("#{id}"), {ratio}, fracw, frach, {ow}, {oh});\n' ' plotman.enqueue(function() {{ \n' ' {plotlyResizeJS} \n' ' pex_resize_slaves($("#{id}"), {ow}, {oh});\n' ' }}, "Resizing Plot {id}" );\n' ' //console.log("Resized {id}");\n' ' }});\n').format(id=plotdivid, ratio=aspect_val, ow=orig_width if orig_width else "null", oh=orig_height if orig_height else "null", plotlyResizeJS=plotly_resize_js) return {'html': plot_html, 'js': full_script}
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, animation_opts=None): """ Draw plotly graphs inside an IPython or Jupyter notebook figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=False) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js 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 using plotly.io.write_image. See https://plot.ly/python/static-image-export/ 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. auto_play (default=True) -- Whether to automatically start the animation sequence if the figure contains frames. Has no effect if the figure does not contain frames. animation_opts (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. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) # We can also download an image of the plot by setting the image to the format you want. e.g. `image='png'` iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png') ``` animation_opts Example: ``` from plotly.offline import iplot figure = {'data': [{'x': [0, 1], 'y': [0, 1]}], 'layout': {'xaxis': {'range': [0, 5], 'autorange': False}, 'yaxis': {'range': [0, 5], 'autorange': False}, 'title': 'Start Title'}, 'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]}, {'data': [{'x': [1, 4], 'y': [1, 4]}]}, {'data': [{'x': [3, 4], 'y': [3, 4]}], 'layout': {'title': 'End Title'}}]} iplot(figure,animation_opts="{frame: {duration: 1}}") ``` """ import plotly.io as pio ipython = get_module('IPython') if not ipython: raise ImportError('`iplot` can only run inside an IPython Notebook.') config = dict(config) if config else {} config.setdefault('showLink', show_link) config.setdefault('linkText', link_text) # Get figure figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) # Handle image request post_script = build_save_image_post_script( image, filename, image_height, image_width, 'iplot') # Show figure pio.show(figure, validate=validate, config=config, auto_play=auto_play, post_script=post_script, animation_opts=animation_opts)
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, animation_opts=None): """ Draw plotly graphs inside an IPython or Jupyter notebook figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=False) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js 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 using plotly.io.write_image. See https://plot.ly/python/static-image-export/ 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. auto_play (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. animation_opts (default=None) -- Dict of custom animation parameters that are used for the automatically started animation on page load. This dict is 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. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) # We can also download an image of the plot by setting the image to the format you want. e.g. `image='png'` iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png') ``` animation_opts Example: ``` from plotly.offline import iplot figure = {'data': [{'x': [0, 1], 'y': [0, 1]}], 'layout': {'xaxis': {'range': [0, 5], 'autorange': False}, 'yaxis': {'range': [0, 5], 'autorange': False}, 'title': 'Start Title'}, 'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]}, {'data': [{'x': [1, 4], 'y': [1, 4]}]}, {'data': [{'x': [3, 4], 'y': [3, 4]}], 'layout': {'title': 'End Title'}}]} iplot(figure, animation_opts={'frame': {'duration': 1}}) ``` """ import plotly.io as pio ipython = get_module('IPython') if not ipython: raise ImportError('`iplot` can only run inside an IPython Notebook.') config = dict(config) if config else {} config.setdefault('showLink', show_link) config.setdefault('linkText', link_text) # Get figure figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) # Handle image request post_script = build_save_image_post_script( image, filename, image_height, image_width, 'iplot') # Show figure pio.show(figure, validate=validate, config=config, auto_play=auto_play, post_script=post_script, animation_opts=animation_opts)
def _plot_html(figure_or_data, config, validate, default_width, default_height, global_requirejs): figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', default_width) height = figure.get('layout', {}).get('height', default_height) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(height) except (ValueError, TypeError): pass else: height = str(height) + 'px' plotdivid = uuid.uuid4() jdata = _json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = _json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) if figure.get('frames', None): jframes = _json.dumps(figure.get('frames', []), cls=utils.PlotlyJSONEncoder) else: jframes = None jconfig = _json.dumps(_get_jconfig(config)) plotly_platform_url = plotly.plotly.get_config().get( 'plotly_domain', 'https://plot.ly') if jframes: script = ''' Plotly.plot( '{id}', {data}, {layout}, {config} ).then(function () {add_frames}).then(function(){animate}) '''.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig, add_frames="{" + "return Plotly.addFrames('{id}',{frames}".format( id=plotdivid, frames=jframes) + ");}", animate="{" + "Plotly.animate('{id}');".format(id=plotdivid) + "}") else: script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig) optional_line1 = ('require(["plotly"], function(Plotly) {{ ' if global_requirejs else '') optional_line2 = ('}});' if global_requirejs else '') plotly_html_div = ( '' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' + optional_line1 + 'window.PLOTLYENV=window.PLOTLYENV || {{}};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '{script}' + optional_line2 + '</script>' '').format(id=plotdivid, script=script, height=height, width=width) return plotly_html_div, plotdivid, width, height
def js_convert(figure_or_data,outfilename, show_link=False, link_text='Export to plot.ly', validate=True): figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', 525) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text config["displaylogo"]=False config["modeBarButtonsToRemove"]= ['sendDataToCloud'] jconfig = json.dumps(config) plotly_platform_url = session.get_session_config().get('plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) script = '\n'.join([ 'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{', ' $(".{id}.loading").remove();', '}})' ]).format(id=plotdivid, data=jdata, layout=jlayout, config=jconfig) html="""<div class="{id} loading" style="color: rgb(50,50,50);"> Drawing...</div> <div id="{id}" style="height: {height}; width: {width};" class="plotly-graph-div"> </div> <script type="text/javascript"> {script} </script> """.format(id=plotdivid, script=script, height=height, width=width) #html = html.replace('\n', '') with open(outfilename, 'wb') as out: out.write(r'<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>') for line in html.split('\n'): out.write(line) out.close() print ('JS Conversion Complete')
def _plot_html(figure_or_data, config, validate, default_width, default_height, global_requirejs, auto_play): figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', default_width) height = figure.get('layout', {}).get('height', default_height) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(height) except (ValueError, TypeError): pass else: height = str(height) + 'px' plotdivid = uuid.uuid4() jdata = _json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = _json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) if figure.get('frames', None): jframes = _json.dumps(figure.get('frames', []), cls=utils.PlotlyJSONEncoder) else: jframes = None jconfig = _json.dumps(_get_jconfig(config)) plotly_platform_url = plotly.plotly.get_config().get('plotly_domain', 'https://plot.ly') if jframes: if auto_play: animate = (".then(function(){" + "Plotly.animate('{id}');".format(id=plotdivid) + "})") else: animate = '' script = ''' if (document.getElementById("{id}")) {{ Plotly.plot( '{id}', {data}, {layout}, {config} ).then(function () {add_frames}){animate} }} '''.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig, add_frames="{" + "return Plotly.addFrames('{id}',{frames}".format( id=plotdivid, frames=jframes ) + ");}", animate=animate ) else: script = """ if (document.getElementById("{id}")) {{ Plotly.newPlot("{id}", {data}, {layout}, {config}); }} """.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig) optional_line1 = ('require(["plotly"], function(Plotly) {{ ' if global_requirejs else '') optional_line2 = ('}});' if global_requirejs else '') plotly_html_div = ( '' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' + optional_line1 + 'window.PLOTLYENV=window.PLOTLYENV || {{}};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '{script}' + optional_line2 + '</script>' '').format( id=plotdivid, script=script, height=height, width=width) return plotly_html_div, plotdivid, width, height
def _plot_html(figure_or_data, show_link, link_text, validate, default_width, default_height): figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', default_width) height = figure.get('layout', {}).get('height', default_height) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text jconfig = json.dumps(config) # TODO: The get_config 'source of truth' should # really be somewhere other than plotly.plotly plotly_platform_url = plotly.plotly.get_config().get('plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format( id=plotdivid, data=jdata, layout=jlayout, config=jconfig) plotly_html_div = ( '' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' 'window.PLOTLYENV=window.PLOTLYENV || {{}};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '{script}' '</script>' '').format( id=plotdivid, script=script, height=height, width=width) return plotly_html_div, plotdivid, width, height