How to use the plotly.graph_objects function in plotly

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 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 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 sloev / metrace / metrace / plot_command.py View on Github external
go.Scatter(
                    name=f"trace: {name}",
                    x=x + x[::-1],
                    y=y_high + y_low[::-1],
                    fillcolor=c,
                    fill="tozeroy",
                    text=[name] * len(x) * 2,
                    line=dict(color="rgba(255,255,255,0)"),
                    hovertemplate="trace: %{text}",
                )
            )

    layout = go.Layout(
        plot_bgcolor="rgba(240,240,240,10)",
        title=title,
        yaxis=go.layout.YAxis(
            range=[min_used, max_used], tickvals=ticks, ticktext=tick_text
        ),
        width=800,
        height=400,
    )

    fig = go.Figure(info_traces + traces, layout)

    return fig
github antoniaelek / fantasy-premier-league / teams.py View on Github external
y=df['form'],
            name=club,
            text = df['description'],     
            mode='lines+markers',
            line=dict(shape='spline', width=4, smoothing=1.3),
            hoverlabel= dict(font=dict(color='#404040'),
                             bordercolor='#404040',
                             bgcolor='white'
            ),
            hovertemplate = "<b>"+club+"</b><br><br><br>Form: %{y}<br>%{text}<br><br>"))
        
    fig.update_layout(
        hovermode='closest',
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        legend=go.layout.Legend(
            traceorder="normal",
            font=dict(color="#eee"),
            bgcolor="rgba(0,0,0,0)"
        )
    )
    
    fig.update_yaxes(title_text="Form",color='#eee',tick0=1,dtick=1,showgrid=False,zeroline=False)
    fig.update_xaxes(title_text="Gameweek",color='#eee',tick0=1,dtick=1,showgrid=True,zeroline=True)

    fig.update_scenes(bgcolor='rgba(0,0,0,0)')

    fig.layout.update(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)')
    chart_studio.plotly.plot(fig, filename="club_form", auto_open=False)
    #plotly.offline.iplot(fig)
github SolarArbiter / solarforecastarbiter-core / solarforecastarbiter / reports / figures / plotly_figures.py View on Github external
if metadata['axis'] not in axis:
            # we're looking at a different kind of forecast than what we wanted
            # to plot
            continue
        pair_idcs = timeseries_value_df['pair_index'] == metadata['pair_index']
        # probably treat axis == None and axis == y separately in the future.
        # currently no need for a separate axis == x treatment either, so
        # removed an if statement on the axis.
        plot_kwargs = line_or_step_plotly(
            metadata['interval_label'])
        data = _fill_timeseries(
            timeseries_value_df[pair_idcs],
            metadata['interval_length'],
        )
        plot_kwargs['marker'] = dict(color=next(palette))
        go_ = go.Scattergl(
            y=data['forecast_values'],
            x=data.index,
            name=_legend_text(metadata['forecast_name']),
            legendgroup=metadata['forecast_name'],
            connectgaps=False,
            **plot_kwargs)
        # collect in list
        gos.append((metadata['pair_index'], go_))
    # Add traces in order of pair index
    for idx, go_ in sorted(gos, key=lambda x: x[0]):
        fig.add_trace(go_)
github scrapinghub / arche / src / arche / figures / tables.py View on Github external
test_results_values.append(results)
        status_values.append("Fail" if result.err_items_count else "Pass")

    values = {
        "Test Name": test_name_values,
        "Tested Fields": tested_fields_values,
        "Result": test_results_values,
        "Status": status_values,
    }
    df = pd.DataFrame.from_dict(values)
    df["Color"] = df.apply(
        lambda row: "rgb(233,81,51)" if row.Status == "Fail" else "rgb(112,194,99)",
        axis="columns",
    )

    trace = go.Table(
        columnwidth=[100, 230, 140, 40],
        header=dict(
            values=list(values.keys()),
            fill=dict(color="gray"),
            align="left",
            font=dict(color="black", size=14),
        ),
        cells=dict(
            values=[df["Test Name"], df["Tested Fields"], df["Result"], df["Status"]],
            fill=dict(color=["lightgrey", "lightgrey", "lightgrey", df["Color"]]),
            font=dict(color="black", size=12),
            align="left",
            height=25,
        ),
    )
github seungjaeryanlee / rldb / parsers / plot.py View on Github external
def plot_single_env(df, env_name, online):
    df = df.dropna(subset=[env_name])
    df = df.sort_values(by=[env_name], ascending=True)
    fig = go.Figure([go.Bar(
        x=df["metadata_agent_nickname"] + df["metadata_paper_title"],
        y=df[env_name],
        text=df[env_name],
        textposition='auto',
        hovertext="<b>Paper: </b>" + df["metadata_paper_title"] + "<br><b>Agent: </b>" + df["metadata_agent_fullname"],
    )])
    fig.update_layout(
        barmode='group',
        xaxis=dict(
            tickmode="array",
            tickvals=df["metadata_agent_nickname"] + df["metadata_paper_title"],
            ticktext=df["metadata_agent_nickname"],
        ),
    )
    fig.show()
    py.plot(fig, filename=env_name, auto_open=True)
github antoniaelek / fantasy-premier-league / teams.py View on Github external
x=df['event'], 
            y=df['difficulty'],
            name=club,          
            mode='lines',
            line=dict(shape='spline', width=4, smoothing=1.3),
            text = df['opponent'] + ' (' + df['where'] + ')',
            hoverlabel= dict(
                font=dict(color='#404040'),
                bordercolor='#404040',
                bgcolor='white'
            ),            
            hovertemplate = "<b>"+club+"</b><br><br>vs %{text}<br><br>"))
        
    fig.update_layout(
        hovermode='x',
        legend=go.layout.Legend(
            traceorder="normal",
            font=dict(color="#eee"),
            bgcolor="rgba(0,0,0,0)"
        )
    )
    
    x_min=df[['event']].iloc[0]-1
    x_max=df[['event']].iloc[-1]+1
    fig.update_yaxes(title_text="Difficulty",color='#eee',showgrid=False, zeroline=False, tick0=1, dtick=1, range=[1.5, 5])
    fig.update_xaxes(title_text="Gameweek",color='#eee',showgrid=True, zeroline=True, tick0=1, dtick=1, range=[x_min, x_max])

    fig.update_scenes(bgcolor='rgba(0,0,0,0)')

    fig.layout.update(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)')
    chart_studio.plotly.plot(fig, filename="easiest_schedule", auto_open=False)
    #plotly.offline.iplot(fig)
github freqtrade / freqtrade / freqtrade / plot / plotting.py View on Github external
def add_indicators(fig, row, indicators: List[str], data: pd.DataFrame) -> make_subplots:
    """
    Generator all the indicator selected by the user for a specific row
    :param fig: Plot figure to append to
    :param row: row number for this plot
    :param indicators: List of indicators present in the dataframe
    :param data: candlestick DataFrame
    """
    for indicator in indicators:
        if indicator in data:
            scatter = go.Scatter(
                x=data['date'],
                y=data[indicator].values,
                mode='lines',
                name=indicator
            )
            fig.add_trace(scatter, row, 1)
        else:
            logger.info(
                'Indicator "%s" ignored. Reason: This indicator is not found '
                'in your strategy.',
                indicator
            )

    return fig
github simonwongwong / Facebook-Messenger-Statistics / chatstat.py View on Github external
if isinstance(length, list):
            fig = make_subplots(
                rows=len(length), cols=1, specs=[[{'type': 'bar'}]] * len(length),
                subplot_titles=[f"Top words with {l} or more letters" for l in length],
            )
            filtered_dfs = [len_filtered_wdf(min_len) for min_len in length]
            graph = []
            for i, df in enumerate(filtered_dfs):
                bar = go.Bar(x=df.index, y=df['count'])
                graph.append(bar)
                fig.add_trace(bar, row=i + 1, col=1)
            fig.update_layout(height=400 * len(length), showlegend=False)

        else:
            filtered_df = len_filtered_wdf(length)
            graph = go.Bar(x=filtered_df.index, y=filtered_df['count'])
            fig = go.Figure(graph)
            fig.update_layout(title_text=f"Top words with {length} or more letters")

        return fig, graph