How to use plotly - 10 common examples

To help you get started, we’ve selected a few plotly examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vpc-ccg / calib / slurm_scripts / calib_scalability_tests_plotting.py View on Github external
trace = go.Scatter(
        name='Time for molNum = {}'.format(num_molecules),
        x=x_list,
        y=y1_list,
        mode='markers+lines',
        marker=dict(
            symbol=key_to_symbol[(num_molecules,'wall_time')],
            size=10,
        ),
        line=dict(
            color='black',
            dash='solid',
        )
    )
    data.append(trace)
    trace = go.Scatter(
        name='RAM for molNum = {}'.format(num_molecules),
        x=x_list,
        y=y2_list,
        yaxis='y2',
        mode='markers+lines',
        marker=dict(
            symbol=key_to_symbol[(num_molecules,'mem')],
            size=10,
        ),
        line=dict(
            color='black',
            dash='longdash',
        )
    )
    print(key_to_symbol[(num_molecules,'mem')],)
    data.append(trace)
github lucasrodes / whatstk / tests / graph / test_figures.py View on Github external
def test_user_interventions_count_linechart():
    df = load_chat_as_df()
    fb = FigureBuilder(df=df)
    fig = fb.user_interventions_count_linechart()
    assert isinstance(fig, go.Figure)
    assert ('data' in fig and 'layout' in fig)
github mwouts / jupytext / tests / notebooks / mirror / ipynb_to_sphinx / World population.py View on Github external
plt.ylabel('Population count (B)')
plt.show()

###############################################################################
# ## Stacked bar plot with plotly

###############################################################################
# Stacked area plots (with cumulated values computed depending on
# selected legends) are
# [on their way](https://github.com/plotly/plotly.js/pull/2960) at Plotly. For
# now we just do a stacked bar plot.

import plotly.offline as offline
import plotly.graph_objs as go

offline.init_notebook_mode()

""
bars = [go.Bar(x=population.index, y=population[zone], name=zone)
        for zone in zones]
fig = go.Figure(data=bars,
                layout=go.Layout(title='World population',
                                 barmode='stack'))
offline.iplot(fig)
github freqtrade / freqtrade / tests / test_plotting.py View on Github external
data = history.load_pair_history(pair=pair, ticker_interval='1m',
                                     datadir=testdatadir, timerange=timerange)
    indicators1 = ["ema10"]
    indicators2 = ["macd"]

    # Generate buy/sell signals and indicators
    strat = DefaultStrategy(default_conf)
    data = strat.analyze_ticker(data, {'pair': pair})
    fig = generate_empty_figure()

    # Row 1
    fig1 = add_indicators(fig=deepcopy(fig), row=1, indicators=indicators1, data=data)
    figure = fig1.layout.figure
    ema10 = find_trace_in_fig_data(figure.data, "ema10")
    assert isinstance(ema10, go.Scatter)
    assert ema10.yaxis == "y"

    fig2 = add_indicators(fig=deepcopy(fig), row=3, indicators=indicators2, data=data)
    figure = fig2.layout.figure
    macd = find_trace_in_fig_data(figure.data, "macd")
    assert isinstance(macd, go.Scatter)
    assert macd.yaxis == "y3"

    # No indicator found
    fig3 = add_indicators(fig=deepcopy(fig), row=3, indicators=['no_indicator'], data=data)
    assert fig == fig3
    assert log_has_re(r'Indicator "no_indicator" ignored\..*', caplog)
github freqtrade / freqtrade / tests / test_plotting.py View on Github external
fig1 = generate_empty_figure()
    # nothing happens when no trades are available
    fig = plot_trades(fig1, None)
    assert fig == fig1
    assert log_has("No trades found.", caplog)
    pair = "ADA/BTC"
    filename = testdatadir / "backtest-result_test.json"
    trades = load_backtest_data(filename)
    trades = trades.loc[trades['pair'] == pair]

    fig = plot_trades(fig, trades)
    figure = fig1.layout.figure

    # Check buys - color, should be in first graph, ...
    trade_buy = find_trace_in_fig_data(figure.data, "trade_buy")
    assert isinstance(trade_buy, go.Scatter)
    assert trade_buy.yaxis == 'y'
    assert len(trades) == len(trade_buy.x)
    assert trade_buy.marker.color == 'green'

    trade_sell = find_trace_in_fig_data(figure.data, "trade_sell")
    assert isinstance(trade_sell, go.Scatter)
    assert trade_sell.yaxis == 'y'
    assert len(trades) == len(trade_sell.x)
    assert trade_sell.marker.color == 'red'
github vantaka2 / crypto_dash_app / app.py View on Github external
def scatter_plot(coin_select, datefilter):
    df = filter_reddit(df_scatter, coin_select, datefilter)
    data = [
        go.Scatter(
            y=df[df['name'] == i]['post_count'],
            x=df[df['name'] == i]['market_cap_usd'],
            opacity=0.8,
            hovertext=df[df['name'] == i]['created'],
            mode = 'markers',
            marker = dict(size = 15),
            name=i

        ) for i in coin_select
    ]
    layout = go.Layout(
        title='Mentions vs Marketcap',
        xaxis=dict(
             title='Marketcap (Log Scale)',
             
        type='log',
        autorange=True,
        
    ),
    hovermode='closest',
    yaxis=dict(
        title='Mention Count',
        
        autorange=True
    )
    )
    figure = {'data':data,
github sdomanskyi / DigitalCellSorter / DigitalCellSorter / VisualizationFunctions.py View on Github external
targets.extend(list(range(len(df.index), len(df.index) + len(df.loc[item]))))
            values.extend([j for j in df.loc[item].values])
            if type(item) is tuple:
                labels.extend([str(item[0]) + ' -> ' + str(jtem[0]) for jtem in df.loc[item].index])
            else:
                labels.extend([str(item) + ' -> ' + str(jtem) for jtem in df.loc[item].index])

        colorscales = [dict(label=label, colorscale=[[0, linksColor], [1, linksColor]]) for label in labels]

        if not nodeColors is None:
            for i in range(len(sources)):
                if nodeColors[sources[i]] == nodeColors[targets[i]]:
                    newColor = ','.join(nodeColors[sources[i]].split(',')[:3] + ['0.6)'])
                    colorscales[i] = dict(label=labels[i], colorscale=[[0, newColor], [1, newColor]])

        fig = go.Figure(data=[go.Sankey(valueformat = '', valuesuffix = '',
            node = dict(pad = 20, thickness = 40, line = dict(color = 'white', width = 0.5), label = nodeLabels, color = nodeColors,),
            link = dict(source = sources, target = targets, value = values, label = labels, colorscales = colorscales, hoverinfo='all'))]) #line ={'color':'rgba(255,0,0,0.8)', 'width':0.1}

        if not title is None:
            fig.update_layout(title_text=title, font_size=10)

        fig.update_layout(margin=dict(l=border, r=border, t=border, b=border))

        try:
            fig.write_image(os.path.join(self.saveDir, self.dataName + nameAppend + '.png'), width=width, height=height, scale=quality)

        except Exception as exception:
            if self.verbose >= 2:
                print('Cannot save static image (likely due to missing orca). Saving to interactive html')
            attemptSavingHTML = True
github KMouratidis / EDA_miner / EDA_miner / apps / analyze / Clustering.py View on Github external
model.fit(df[xvars])

    # TODO: Find a meaningful way (metric) to notify the user of model score.
    try:
        layout = [[html.H4(f"Clustering model scored: {model.score(df[xvars])}")]]
    except AttributeError:
        # model without a score function
        layout = [[html.H4(f"No score for this method.")]]

    labels = model.labels_
    # TODO: If Y is given, visualize the (in)correctly grouped points.
    # If we have >=2 variables, visualize the clusters
    if len(xvars) >= 3:

        trace1 = go.Scatter3d(x=df[xvars[0]],
                              y=df[xvars[1]],
                              z=df[xvars[2]],
                              showlegend=False,
                              mode='markers',
                              marker=dict(
                                  color=labels.astype(np.float),
                                  line={'color': 'black', 'width': 1}
                              ))

        layout += [{
            'data': [trace1],
            'layout': layouts.default_2d(xvars[0], xvars[1])
        }]

    elif len(xvars) == 2:
        trace = scatterplot(df[xvars[0]], df[xvars[1]],
github DeniseCaiLab / minian / minian / visualization_ply.py View on Github external
def _update_spatial_unit(self, uid, rely1, rely2, rely3, rely4, rely5,
                             state):
        print('update_spatial_unit')
        _initial = False
        _update = False
        if not state:
            _initial = True
        elif not state['data'][0]['customdata'] == uid:
            _update = True
        if _initial or _update:
            cur_A = self.cnmf['A'].sel(unit_id=uid if not uid is None else [])
            trace = [
                go.Heatmap(
                    x=cur_A.coords['width'].values,
                    y=cur_A.coords['height'].values,
                    z=cur_A.values,
                    colorscale='Viridis',
                    colorbar=dict(x=1),
                    hoverinfo='none',
                    customdata=uid)
            ]
            if _update:
                state.update(data=trace)
        if _initial:
            layout = go.Layout(
                title="Spatial Component of unit: {}".format(uid),
                xaxis=dict(
                    title='width',
                    range=[0, self._w],
github materialsproject / MPWorks / mpworks / osti_doi / __main__.py View on Github external
stream_ids=stream_ids
        )
        today = datetime.date.today()
        counts = [
            matad.matcoll.count(), matad.doicoll.count(),
            len(matad.get_all_dois())
        ]
        names = ['materials', 'requested DOIs', 'validated DOIs']
        data = Data([
            Scatter(
                x=[today], y=[counts[idx]], name=names[idx],
                stream=dict(token=stream_ids[idx], maxpoints=10000)
            ) for idx,count in enumerate(counts)
        ])
        filename = 'dois_{}'.format(today)
        print py.plot(data, filename=filename, auto_open=False)
else:
    # generate records for either n or all (n=0) not-yet-submitted materials 
    # OR generate records for specific materials (submitted or not)
    osti = OstiRecord(l=args.l, n=args.n, db_yaml=db_yaml)
    osti.submit()