How to use the plotly.graph_objects.Figure 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 Epistimio / orion / src / orion / plotting / backend_plotly.py View on Github external
df['best_id'] = _get_best_ids(df)

        return df

    ORDER_KEYS = ['suggested', 'reserved', 'completed']

    if not experiment:
        raise ValueError("Parameter 'experiment' is None")

    if order_by not in ORDER_KEYS:
        raise ValueError(f"Parameter 'order_by' is not one of {ORDER_KEYS}")

    trials = list(filter(lambda trial: trial.status == 'completed', experiment.fetch_trials()))
    df = build_frame(trials)

    fig = go.Figure()

    fig.add_scatter(y=df['objective'],
                    mode='markers',
                    name='trials',
                    customdata=list(zip(df['id'], df[order_by], df['params'])),
                    hovertemplate=_template_trials(verbose_hover))
    fig.add_scatter(y=df['best'],
                    mode='lines',
                    name='best-to-date',
                    customdata=list(zip(df['best_id'], df['best'])),
                    hovertemplate=_template_best())

    y_axis_label = f"{trials[0].objective.type.capitalize()} '{trials[0].objective.name}'"
    fig.update_layout(title=f"Regret for experiment '{experiment.name}'",
                      xaxis_title=f"Trials ordered by {order_by} time",
                      yaxis_title=y_axis_label)
github GUDHI / gudhi-devel / src / python / example / plot_rips_complex.py View on Github external
#!/usr/bin/env python

import numpy as np
import gudhi
points = np.array(gudhi.read_off('../../data/points/Kl.off'))
rc = gudhi.RipsComplex(points=points, max_edge_length=.2)
st = rc.create_simplex_tree(max_dimension=2)
# We are only going to plot the triangles
triangles = np.array([s[0] for s in st.get_skeleton(2) if len(s[0])==3])

# First possibility: plotly
import plotly.graph_objects as go
fig = go.Figure(data=[
    go.Mesh3d(
        # Use the first 3 coordinates, but we could as easily pick others
        x=points[:,0],
        y=points[:,1],
        z=points[:,2],
        i = triangles[:,0],
        j = triangles[:,1],
        k = triangles[:,2],
    )
])
fig.show()

# Second possibility: matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
github capocchi / DEVSimPy / Domain / Collector / Plotly_For_Class.py View on Github external
for c in classes:
            barsX.append(c['label'])
            barsY.append(c['score'])
                
        bars = go.Bar(
            x=barsX,
            y=barsY,
            name='Classification'
        )        

        data = [bars]
        layout = go.Layout(
            xaxis=dict(tickangle=-45)
        )

        fig = go.Figure(data=data, layout=layout)
        #py.iplot(fig, filename='angled-text-bar')
                
        self.plotUrl = py.plot(data, filename='class', auto_open=False, fileopt='new')
        print((self.plotUrl))
        
        self.state['sigma'] = 0
github fullstorydev / pathing-utils / pathutils / sankey_funnel.py View on Github external
def plot_funnel(title: str, events: pd.DataFrame, funnel: list, useResolvedUrls: bool, cutoff: int=10):
    """Plot sankey diagram for a funnel

    :param title: title for the sankey diagram
    :param events: events dataframe
    :param funnel: funnel to be plotted
    :param useResolvedUrls: indicates whether original or resolved URLs should be used
    :param cutoff: number of inflow/outflow nodes to plot for each sankey node (all remaining nodes get grouped into Other)
    :return:
    """
    labels, colors, sources, targets, values, title = get_funnel_lists(title, events, funnel, useResolvedUrls, cutoff)

    fig = gobj.Figure(data=[gobj.Sankey(
        arrangement="freeform",
        node=dict(
            pad=15,
            thickness=20,
            line=dict(color="black", width=0.5),
            label=labels,
            color=colors
        ),
        link=dict(
            source=sources,
            target=targets,
            value=values,
        ))])

    fig.update_layout(title_text=title, font_size=12)
    fig.show()
github SolarArbiter / solarforecastarbiter-core / solarforecastarbiter / reports / figures / plotly_figures.py View on Github external
DataFrame of timeseries data. See
        :py:func:`solarforecastarbiter.reports.figures.construct_timeseries_dataframe`
        for format.
    timeseries_meta_df: pandas.DataFrame
        DataFrame of metadata for each Observation Forecast pair. See
        :py:func:`solarforecastarbiter.reports.figures.construct_timeseries_dataframe`
        for format.

    Returns
    -------
    plotly.Figure
    """  # NOQA
    scatter_range = _get_scatter_limits(timeseries_value_df)

    palette = cycle(PALETTE)
    fig = go.Figure()
    # accumulate labels and plot objects for manual legend
    for fxhash in np.unique(timeseries_meta_df['forecast_hash']):
        metadata = _extract_metadata_from_df(
            timeseries_meta_df, fxhash, 'forecast_hash')
        if metadata['axis'] == 'x':
            # don't know how to represent probability forecasts on a
            # physical value vs. physical value plot.
            continue
        pair_idcs = timeseries_value_df['pair_index'] == metadata['pair_index']
        data = timeseries_value_df[pair_idcs]

        fig.add_trace(go.Scattergl(
            x=data['observation_values'],
            y=data['forecast_values'],
            name=_legend_text(metadata['forecast_name']),
            showlegend=True,
github qzhu2017 / PyXtal / pyxtal / XRD.py View on Github external
x, y, labels = [], [], []
        for i in range(len(self.pxrd)):
            theta2, d, h, k, l, I = self.pxrd[i]
            h, k, l = int(h), int(k), int(l)
            if I > minimum_I:
                label = '<br>2θ: {:6.2f}<br>d: {:6.4f}<br>I: {:6.4f}<br>hkl: ({:d}{:d}{:d})'.format(theta2, d, I, h, k, l)
                x.append(theta2)
                y.append(-0.1)
                labels.append(label)

        trace1 = go.Bar(x=x, y=y, text=labels,
                        hovertemplate = "%{text}",
                        width=0.2, name='Index')
        trace2 = go.Scatter(x=self.spectra[0], y=self.spectra[1], name='Profile')

        fig = go.Figure(data=[trace2, trace1])
        fig.update_layout(xaxis_title = '2θ ({:.4f} Å)'.format(self.wavelength),
                          yaxis_title = 'Intensity',
                          title = 'PXRD of '+self.name)

        if os.environ['_'].find('jupyter') == -1:
            if html is None:
                return fig.to_html()
            else:
                fig.write_html(html)
        else:
            print("This is running on Jupyter Notebook")
            return fig
github antoniaelek / fantasy-premier-league / teams.py View on Github external
def next_fixtures_plot(season, base_path, data, limit_diff=100.0):
    clubs_h = list(get_upcoming_fixtures_data(base_path, season)['team_h'].unique())
    clubs_a = list(get_upcoming_fixtures_data(base_path, season)['team_a'].unique())
    clubs = sorted(set(clubs_h + clubs_a))
    
    fig = go.Figure()

    for club in clubs:
        df = data.loc[club]

        if (df.iloc[-1]['sum_difficulty']>limit_diff):
            continue
        
        fig.add_trace(go.Scatter(
            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'),
github s-brez / trading-server / model.py View on Github external
if features[-1][0] == longs['time'][-1]:
                    direction = "LONG"
                    entry_price = longs['price'][-1]
                    entry_ts = longs['time'][-1]
                    signal = True

                elif features[-1][0] == shorts['time'][-1]:
                    direction = "SHORT"
                    entry_price = shorts['price'][-1]
                    entry_ts = shorts['time'][-1]
                    signal = True

                if signal:

                    # Plot the signal.
                    chart = go.Figure(
                        data=[

                            # Bars.
                            go.Ohlc(
                                x=op_data[timeframe].index,
                                open=op_data[timeframe]['open'],
                                high=op_data[timeframe]['high'],
                                low=op_data[timeframe]['low'],
                                close=op_data[timeframe]['close'],
                                name="Bars",
                                increasing_line_color='black',
                                decreasing_line_color='black'),

                            # EMA10.
                            go.Scatter(
                                x=op_data[timeframe].index,
github MolSSI / QCFractal / qcfractal / interface / visualization.py View on Github external
Nweft = len(labels)
    lenS = 0.2
    gapT = 0.04
    positions = range(-1, -1 * Nweft - 1, -1)
    posnS = []
    for weft in range(Nweft):
        posnS.extend([positions[weft] + lenS, positions[weft] - lenS, None])
    posnT = []
    for weft in range(Nweft - 1):
        posnT.extend([positions[weft] - lenS - gapT, positions[weft + 1] + lenS + gapT, None])
    posnM = []
    xticks = [-0.5 * xlimit, -0.25 * xlimit, 0.0, 0.25 * xlimit, 0.5 * xlimit]

    # initialize plot
    import plotly.graph_objects as go
    fig = go.Figure()

    fig.update_layout(
        autosize=False,
        width=72 * 11,
        height=72 * Nweft * 0.8,
        margin=dict(b=36, l=7, r=7, t=34, pad=0),
        showlegend=False,
        xaxis=dict(range=[-xlimit, xlimit], tickvals=xticks, zeroline=True, zerolinewidth=3),
        yaxis=dict(range=[-1 * Nweft - 1, 0], showticklabels=False),
    )
    
    # label plot and tiers
    annot = []
    annot.append(go.layout.Annotation(
        x=-0.9 * xlimit,
        y=-0.25,