Python plotly.offline.iplot() Examples

The following are 11 code examples of plotly.offline.iplot(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module plotly.offline , or try the search function .
Example #1
Source File: explorer.py    From lens with Apache License 2.0 6 votes vote down vote up
def _render(fig, showlegend=None):
    """Plot a matploltib or plotly figure"""
    if isinstance(fig, plt.Figure):
        fig = plotly.tools.mpl_to_plotly(fig, **PLOTLY_TO_MPL_KWS)

    if showlegend is not None:
        fig.layout["showlegend"] = showlegend

    if not IN_NOTEBOOK:
        message = "Lens explorer can only plot in a Jupyter notebook"
        logger.error(message)
        raise ValueError(message)
    else:
        if not py.offline.__PLOTLY_OFFLINE_INITIALIZED:
            py.init_notebook_mode()
        return py.iplot(fig, **PLOTLY_KWS) 
Example #2
Source File: utils.py    From word-mesh with MIT License 6 votes vote down vote up
def save_wordmesh_as_html(self, coordinates, filename='temp-plot.html', 
                              animate=False, autozoom=True, notebook_mode=False):

        zoom = 1
        labels = ['default label']
        traces = []
        if animate:
            for i in range(coordinates.shape[0]):
                
                traces.append(self._get_trace(coordinates[i]))
                labels = list(map(str,range(coordinates.shape[0])))
                
        else:

            if autozoom:
                zoom = self._get_zoom(coordinates)
            traces = [self._get_trace(coordinates, zoom=zoom)]
            
        layout = self._get_layout(labels, zoom=zoom)
            
        fig = self.generate_figure(traces, labels, layout)
        
        if notebook_mode:
            py.init_notebook_mode(connected=True)
            py.iplot(fig, filename=filename, show_link=False)
        else:
            py.plot(fig, filename=filename, auto_open=False, show_link=False) 
Example #3
Source File: viz.py    From ConvLab with MIT License 5 votes vote down vote up
def plot(*args, **kwargs):
    if util.is_jupyter():
        return iplot(*args, **kwargs) 
Example #4
Source File: VisPlotly.py    From NURBS-Python with MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        super(VisConfig, self).__init__(**kwargs)
        self.dtype = np.float
        # Set Plotly custom variables
        self.figure_image_filename = "temp-figure"
        self.figure_image_format = "png"
        self.figure_filename = "temp-plot.html"

        # Enable online plotting (default is offline plotting as it works perfectly without any issues)
        # @see: https://plot.ly/python/getting-started/#initialization-for-online-plotting
        online_plotting = kwargs.get('online', False)

        # Detect jupyter and/or ipython environment
        try:
            get_ipython
            from plotly.offline import download_plotlyjs, init_notebook_mode
            init_notebook_mode(connected=True)
            self.plotfn = iplot if online_plotting else plotly.offline.iplot
            self.no_ipython = False
        except NameError:
            self.plotfn = plot if online_plotting else plotly.offline.plot
            self.no_ipython = True

        # Get keyword arguments
        self.display_ctrlpts = kwargs.get('ctrlpts', True)
        self.display_evalpts = kwargs.get('evalpts', True)
        self.display_bbox = kwargs.get('bbox', False)
        self.display_trims = kwargs.get('trims', True)
        self.display_legend = kwargs.get('legend', True)
        self.display_axes = kwargs.get('axes', True)
        self.axes_equal = kwargs.get('axes_equal', True)
        self.figure_size = kwargs.get('figure_size', [1024, 768])
        self.trim_size = kwargs.get('trim_size', 1)
        self.line_width = kwargs.get('line_width', 2) 
Example #5
Source File: plot.py    From sound_field_analysis-py with MIT License 5 votes vote down vote up
def plot3Dgrid(rows, cols, viz_data, style, normalize=True, title=None):
    if len(viz_data) > rows * cols:
        raise ValueError('Number of plot data is more than the specified rows and columns.')
    fig = subplots.make_subplots(rows, cols, specs=[[{'is_3d': True}] * cols] * rows, print_grid=False)

    if style == 'flat':
        layout_3D = dict(
            xaxis=dict(range=[0, 360]),
            yaxis=dict(range=[0, 181]),
            aspectmode='manual',
            aspectratio=dict(x=3.6, y=1.81, z=1)
        )
    else:
        layout_3D = dict(
            xaxis=dict(range=[-1, 1]),
            yaxis=dict(range=[-1, 1]),
            zaxis=dict(range=[-1, 1]),
            aspectmode='cube'
        )

    rows, cols = _np.mgrid[1:rows + 1, 1: cols + 1]
    rows = rows.flatten()
    cols = cols.flatten()
    for IDX in range(0, len(viz_data)):
        cur_row = int(rows[IDX])
        cur_col = int(cols[IDX])
        fig.add_trace(genVisual(viz_data[IDX], style=style, normalize=normalize), cur_row, cur_col)
        fig.layout[f'scene{IDX + 1:d}'].update(layout_3D)

    if title is not None:
        fig.layout.update(title=title)
        filename = f'{title}.html'
    else:
        filename = f'{current_time()}.html'

    if env_info() == 'jupyter_notebook':
        plotly_off.iplot(fig)
    else:
        plotly_off.plot(fig, filename=filename) 
Example #6
Source File: grid_plotly.py    From lantern with Apache License 2.0 5 votes vote down vote up
def plotly_grid(data, indexed=True):
    return iplot(ff.create_table(data), filename='index_table_pd') 
Example #7
Source File: by_plotly.py    From OnePy with MIT License 5 votes vote down vote up
def plot2(self, ticker=None, notebook=False):

        returns_df = self.balance_df.pct_change(
        ).dropna()

        returns_df.columns = ['returns']
        fig = plotly.tools.make_subplots(
            rows=5, cols=2,
            shared_xaxes=True,
            vertical_spacing=0.001)

        fig['layout'].update(height=1500)

        self.append_trace(fig, self.positions_df, 2, 1)
        self.append_trace(fig, self.balance_df, 3, 1)
        self.append_trace(fig, self.holding_pnl_df, 4, 1)
        self.append_trace(fig, self.commission_df, 5, 1)
        self.append_trace(fig, self.margin_df, 1, 1)
        self.append_trace(fig, returns_df, 2, 2, 'bar')
        # fig['layout']['showlegend'] = True

        if notebook:
            plotly.offline.init_notebook_mode()
            py.iplot(fig, filename='OnePy_plot.html', validate=False)
        else:
            py.plot(fig, filename='OnePy_plot.html', validate=False) 
Example #8
Source File: viz.py    From SLM-Lab with MIT License 5 votes vote down vote up
def plot(*args, **kwargs):
    if util.is_jupyter():
        return iplot(*args, **kwargs) 
Example #9
Source File: plot.py    From sound_field_analysis-py with MIT License 4 votes vote down vote up
def showTrace(trace, layout=None, title=None):
    """ Wrapper around Plotly's offline .plot() function

    Parameters
    ----------
    trace : plotly_trace
        Plotly generated trace to be displayed offline
    layout : plotly.graph_objs.Layout, optional
        Layout of plot to be displayed offline
    title : str, optional
        Title of plot to be displayed offline
    # colorize : bool, optional
    #     Toggles bw / colored plot [Default: True]

    Returns
    -------
    fig : plotly_fig_handle
        JSON representation of generated figure
    """
    if layout is None:
        layout = go.Layout(
            scene=dict(
                xaxis=dict(range=[-1, 1]),
                yaxis=dict(range=[-1, 1]),
                zaxis=dict(range=[-1, 1]),
                aspectmode='cube'
            )
        )
    # Wrap trace in array if needed
    if not isinstance(trace, list):
        trace = [trace]

    fig = go.Figure(
        data=trace,
        layout=layout
    )

    if title is not None:
        fig.layout.update(title=title)
        filename = f'{title}.html'
    else:
        try:
            filename = f'{fig.layout.title}.html'
        except TypeError:
            filename = f'{current_time()}.html'

    # if colorize:
    #    data[0].autocolorscale = False
    #    data[0].surfacecolor = [0, 0.5, 1]
    if env_info() == 'jupyter_notebook':
        plotly_off.init_notebook_mode()
        plotly_off.iplot(fig)
    else:
        plotly_off.plot(fig, filename=filename)

    return fig 
Example #10
Source File: offline.py    From lddmm-ot with MIT License 4 votes vote down vote up
def get_image_download_script(caller):
    """
    This function will return a script that will download an image of a Plotly
    plot.

    Keyword Arguments:
    caller ('plot', 'iplot') -- specifies which function made the call for the
        download script. If `iplot`, then an extra condition is added into the
        download script to ensure that download prompts aren't initiated on
        page reloads.
    """

    if caller == 'iplot':
        check_start = 'if(document.readyState == \'complete\') {{'
        check_end = '}}'
    elif caller == 'plot':
        check_start = ''
        check_end = ''
    else:
        raise ValueError('caller should only be one of `iplot` or `plot`')

    return(
             ('<script>'
              'function downloadimage(format, height, width,'
              ' filename) {{'
              'var p = document.getElementById(\'{plot_id}\');'
              'Plotly.downloadImage(p, {{format: format, height: height, '
              'width: width, filename: filename}});'
              '}};' +
              check_start +
              'if(confirm(\'Do you want to save this image as '
              '{filename}.{format}?\\n\\n'
              'For higher resolution images and more export options, '
              'consider making requests to our image servers. Type: '
              'help(py.image) for more details.'
              '\')) {{'
              'downloadimage(\'{format}\', {height}, {width}, '
              '\'{filename}\');}}' +
              check_end +
              '</script>'
              )
    ) 
Example #11
Source File: by_plotly.py    From OnePy with MIT License 4 votes vote down vote up
def plot(self, ticker=None, notebook=False):

        fig = plotly.tools.make_subplots(
            rows=5, cols=1,
            shared_xaxes=True,
            vertical_spacing=0.001,
            specs=[[{}],
                   [{}],
                   [{'rowspan': 2}],
                   [None],
                   [{}]],)

        # fig['layout'].update(height=1500)

        if isinstance(ticker, str):
            ticker = [ticker]

        for i in ticker:
            close_df = self.ohlc_df(i)[['close']]
            close_df.columns = [i]
            #  volume_df = self.ohlc_df(i)[['volume']]
            #  volume_df.columns = [i+' volume']
            self.append_trace(fig, close_df, 3, 1)
            #  self.append_trace(fig, volume_df, 3, 1,
            #  plot_type='bar', legendly_visible=True)
            #  fig['data'][-1].update(dict(yaxis='y6', opacity=0.5))

        #  for i in ticker:
            #  self.append_candlestick_trace(fig, self.ohlc_df(i), 3, 1, i)

        self.append_trace(fig, self.balance_df, 1, 1)
        self.append_trace(fig, self.cash_df, 1, 1)
        self.append_trace(fig, self.holding_pnl_df, 2, 1)
        self.append_trace(fig, self.commission_df, 2,
                          1, legendly_visible=True)
        self.append_trace(fig, self.positions_df, 5, 1)

        total_holding_pnl = sum((i[i.columns[0]] for i in self.holding_pnl_df))
        total_holding_pnl = pd.DataFrame(total_holding_pnl)
        total_holding_pnl.columns = ['total_holding_pnl']
        self.append_trace(fig, total_holding_pnl, 2, 1)

        fig['layout']['yaxis'].update(
            dict(overlaying='y3', side='right', showgrid=False))
        # fig['layout']['xaxis']['type'] = 'category'
        # fig['layout']['xaxis']['rangeslider']['visible'] = False
        # fig['layout']['xaxis']['tickangle'] = 45
        fig['layout']['xaxis']['visible'] = False
        fig['layout']['hovermode'] = 'closest'
        fig['layout']['xaxis']['rangeslider']['visible'] = False

        if notebook:
            plotly.offline.init_notebook_mode()
            py.iplot(fig, filename='OnePy_plot.html', validate=False)
        else:
            py.plot(fig, filename='OnePy_plot.html', validate=False)