Python plotly.graph_objs.Scatter() Examples

The following are 30 code examples of plotly.graph_objs.Scatter(). 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.graph_objs , or try the search function .
Example #1
Source File: backtest.py    From CoinTK with MIT License 8 votes vote down vote up
def plot_results(results, plot_name='temp-plot.html'):
    '''
        results is a list of dictionaries, each of which defines a trace
         e.g. [{'x': x_data, 'y': y_data, 'name': 'plot_name'}, {...}, {...}]

        Each dictionary's key-value pairs will be passed into go.Scatter
         to generate a trace on the graph

    '''
    traces = []

    for input_args in results:
        traces.append(go.Scatter(**input_args))

    layout = go.Layout(
        title='Trading performance over time',
        yaxis=dict(
            title='Value (USD)'
        ),
    )
    plot(go.Figure(data=traces, layout=layout), filename=plot_name) 
Example #2
Source File: utils.py    From PlaNet with MIT License 8 votes vote down vote up
def lineplot(xs, ys_population, title, path='', xaxis='episode'):
  max_colour, mean_colour, std_colour, transparent = 'rgb(0, 132, 180)', 'rgb(0, 172, 237)', 'rgba(29, 202, 255, 0.2)', 'rgba(0, 0, 0, 0)'

  if isinstance(ys_population[0], list) or isinstance(ys_population[0], tuple):
    ys = np.asarray(ys_population, dtype=np.float32)
    ys_min, ys_max, ys_mean, ys_std, ys_median = ys.min(1), ys.max(1), ys.mean(1), ys.std(1), np.median(ys, 1)
    ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

    trace_max = Scatter(x=xs, y=ys_max, line=Line(color=max_colour, dash='dash'), name='Max')
    trace_upper = Scatter(x=xs, y=ys_upper, line=Line(color=transparent), name='+1 Std. Dev.', showlegend=False)
    trace_mean = Scatter(x=xs, y=ys_mean, fill='tonexty', fillcolor=std_colour, line=Line(color=mean_colour), name='Mean')
    trace_lower = Scatter(x=xs, y=ys_lower, fill='tonexty', fillcolor=std_colour, line=Line(color=transparent), name='-1 Std. Dev.', showlegend=False)
    trace_min = Scatter(x=xs, y=ys_min, line=Line(color=max_colour, dash='dash'), name='Min')
    trace_median = Scatter(x=xs, y=ys_median, line=Line(color=max_colour), name='Median')
    data = [trace_upper, trace_mean, trace_lower, trace_min, trace_max, trace_median]
  else:
    data = [Scatter(x=xs, y=ys_population, line=Line(color=mean_colour))]
  plotly.offline.plot({
    'data': data,
    'layout': dict(title=title, xaxis={'title': xaxis}, yaxis={'title': title})
  }, filename=os.path.join(path, title + '.html'), auto_open=False) 
Example #3
Source File: utils.py    From NoisyNet-A3C with MIT License 7 votes vote down vote up
def plot_line(xs, ys_population):
  max_colour = 'rgb(0, 132, 180)'
  mean_colour = 'rgb(0, 172, 237)'
  std_colour = 'rgba(29, 202, 255, 0.2)'

  ys = torch.Tensor(ys_population)
  ys_min = ys.min(1)[0].squeeze()
  ys_max = ys.max(1)[0].squeeze()
  ys_mean = ys.mean(1).squeeze()
  ys_std = ys.std(1).squeeze()
  ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

  trace_max = Scatter(x=xs, y=ys_max.numpy(), line=Line(color=max_colour, dash='dash'), name='Max')
  trace_upper = Scatter(x=xs, y=ys_upper.numpy(), line=Line(color='transparent'), name='+1 Std. Dev.', showlegend=False)
  trace_mean = Scatter(x=xs, y=ys_mean.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color=mean_colour), name='Mean')
  trace_lower = Scatter(x=xs, y=ys_lower.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color='transparent'), name='-1 Std. Dev.', showlegend=False)
  trace_min = Scatter(x=xs, y=ys_min.numpy(), line=Line(color=max_colour, dash='dash'), name='Min')

  plotly.offline.plot({
    'data': [trace_upper, trace_mean, trace_lower, trace_min, trace_max],
    'layout': dict(title='Rewards',
                   xaxis={'title': 'Step'},
                   yaxis={'title': 'Average Reward'})
  }, filename='rewards.html', auto_open=False) 
Example #4
Source File: test.py    From Rainbow with MIT License 7 votes vote down vote up
def _plot_line(xs, ys_population, title, path=''):
  max_colour, mean_colour, std_colour, transparent = 'rgb(0, 132, 180)', 'rgb(0, 172, 237)', 'rgba(29, 202, 255, 0.2)', 'rgba(0, 0, 0, 0)'

  ys = torch.tensor(ys_population, dtype=torch.float32)
  ys_min, ys_max, ys_mean, ys_std = ys.min(1)[0].squeeze(), ys.max(1)[0].squeeze(), ys.mean(1).squeeze(), ys.std(1).squeeze()
  ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

  trace_max = Scatter(x=xs, y=ys_max.numpy(), line=Line(color=max_colour, dash='dash'), name='Max')
  trace_upper = Scatter(x=xs, y=ys_upper.numpy(), line=Line(color=transparent), name='+1 Std. Dev.', showlegend=False)
  trace_mean = Scatter(x=xs, y=ys_mean.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color=mean_colour), name='Mean')
  trace_lower = Scatter(x=xs, y=ys_lower.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color=transparent), name='-1 Std. Dev.', showlegend=False)
  trace_min = Scatter(x=xs, y=ys_min.numpy(), line=Line(color=max_colour, dash='dash'), name='Min')

  plotly.offline.plot({
    'data': [trace_upper, trace_mean, trace_lower, trace_min, trace_max],
    'layout': dict(title=title, xaxis={'title': 'Step'}, yaxis={'title': title})
  }, filename=os.path.join(path, title + '.html'), auto_open=False) 
Example #5
Source File: draw.py    From textprep with MIT License 7 votes vote down vote up
def _draw_scatter(all_vocabs, all_freqs, output_prefix):
    colors = [(s and t) and (s < t and s / t or t / s) or 0
              for s, t in all_freqs]
    colors = [c and np.log(c) or 0 for c in colors]
    trace = go.Scattergl(
        x=[s for s, t in all_freqs],
        y=[t for s, t in all_freqs],
        mode='markers',
        text=all_vocabs,
        marker=dict(color=colors, showscale=True, colorscale='Viridis'))
    layout = go.Layout(
        title='Scatter plot of shared tokens',
        hovermode='closest',
        xaxis=dict(title='src freq', type='log', autorange=True),
        yaxis=dict(title='trg freq', type='log', autorange=True))

    fig = go.Figure(data=[trace], layout=layout)
    py.plot(
        fig, filename='{}_scatter.html'.format(output_prefix), auto_open=False) 
Example #6
Source File: utils.py    From Dist-A3C with MIT License 7 votes vote down vote up
def plot_line(xs, ys_population, path=''):
  max_colour, mean_colour, std_colour = 'rgb(0, 132, 180)', 'rgb(0, 172, 237)', 'rgba(29, 202, 255, 0.2)'

  ys = torch.Tensor(ys_population)
  ys_min = ys.min(1)[0].squeeze()
  ys_max = ys.max(1)[0].squeeze()
  ys_mean = ys.mean(1).squeeze()
  ys_std = ys.std(1).squeeze()
  ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

  trace_max = Scatter(x=xs, y=ys_max.numpy(), line=Line(color=max_colour, dash='dash'), name='Max')
  trace_upper = Scatter(x=xs, y=ys_upper.numpy(), line=Line(color='transparent'), name='+1 Std. Dev.', showlegend=False)
  trace_mean = Scatter(x=xs, y=ys_mean.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color=mean_colour), name='Mean')
  trace_lower = Scatter(x=xs, y=ys_lower.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color='transparent'), name='-1 Std. Dev.', showlegend=False)
  trace_min = Scatter(x=xs, y=ys_min.numpy(), line=Line(color=max_colour, dash='dash'), name='Min')

  plotly.offline.plot({
    'data': [trace_upper, trace_mean, trace_lower, trace_min, trace_max],
    'layout': dict(title='Rewards',
                   xaxis={'title': 'Step'},
                   yaxis={'title': 'Average Reward'})
  }, filename=os.path.join(path, 'rewards.html'), auto_open=False) 
Example #7
Source File: Data_Grabber.py    From Crypto_Trader with MIT License 7 votes vote down vote up
def update_spread():
    global selected_dropdown_value
    global data
    prices = data.get_prices(selected_dropdown_value)
    prices = [list(p) for p in zip(*prices)]
    if len(prices) > 0:
        traces = []
        trace = go.Scatter(x=list(prices[3]),
                           y=list(prices[2]),
                           name='spread',
                           line=dict(color='rgb(114, 186, 59)'),
                           fill='tozeroy',
                           fillcolor='rgba(114, 186, 59, 0.5)',
                           mode='none')
        traces.append(trace)

        return {
            'data': traces,
            'layout': dict(title="Spread")
        } 
Example #8
Source File: Data_Grabber.py    From Crypto_Trader with MIT License 7 votes vote down vote up
def update_market_prices():
    global selected_dropdown_value
    global data
    prices = data.get_prices(selected_dropdown_value)
    prices = [list(p) for p in zip(*prices)]
    if len(prices) > 0:
        traces = []
        x = list(prices[3])
        for i, key in enumerate(['bid', 'ask']):
            trace = go.Scatter(x=x,
                               y=prices[i],
                               name=key,
                               opacity=0.8)
            traces.append(trace)
        return {
            'data': traces,
            'layout': dict(title="Market Prices")
        } 
Example #9
Source File: visualization.py    From bigcode-tools with MIT License 7 votes vote down vote up
def create_interactive_scatter_plot(embeddings_2d, labels, output=None):
    clusters_count = compute_clusters_count(labels)
    data = []
    for i in range(clusters_count):
        indexes = labels[labels.Cluster == i].index.values
        label_column = "value" if "value" in labels.columns else "type"
        trace = go.Scatter(
            x=embeddings_2d[indexes, 0],
            y=embeddings_2d[indexes, 1],
            mode="markers",
            text=labels.loc[indexes][label_column].values,
            marker={"color": SVG_COLORS[i]}
        )
        data.append(trace)

    kwargs = {"filename": output} if output else {}
    plotly.offline.plot(data, **kwargs) 
Example #10
Source File: utils.py    From ACER with MIT License 7 votes vote down vote up
def plot_line(xs, ys_population, save_dir):
  max_colour = 'rgb(0, 132, 180)'
  mean_colour = 'rgb(0, 172, 237)'
  std_colour = 'rgba(29, 202, 255, 0.2)'

  ys = torch.tensor(ys_population)
  ys_min = ys.min(1)[0].squeeze()
  ys_max = ys.max(1)[0].squeeze()
  ys_mean = ys.mean(1).squeeze()
  ys_std = ys.std(1).squeeze()
  ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

  trace_max = Scatter(x=xs, y=ys_max.numpy(), line=Line(color=max_colour, dash='dash'), name='Max')
  trace_upper = Scatter(x=xs, y=ys_upper.numpy(), line=Line(color='transparent'), name='+1 Std. Dev.', showlegend=False)
  trace_mean = Scatter(x=xs, y=ys_mean.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color=mean_colour), name='Mean')
  trace_lower = Scatter(x=xs, y=ys_lower.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color='transparent'), name='-1 Std. Dev.', showlegend=False)
  trace_min = Scatter(x=xs, y=ys_min.numpy(), line=Line(color=max_colour, dash='dash'), name='Min')

  plotly.offline.plot({
    'data': [trace_upper, trace_mean, trace_lower, trace_min, trace_max],
    'layout': dict(title='Rewards',
                   xaxis={'title': 'Step'},
                   yaxis={'title': 'Average Reward'})
  }, filename=os.path.join(save_dir, 'rewards.html'), auto_open=False) 
Example #11
Source File: crossfilter-hover-line.py    From dash-recipes with MIT License 7 votes vote down vote up
def create_time_series(dff, column, title):
    return {
        'data': [go.Scatter(
            x=dff['year'],
            y=dff[column],
            mode='lines+markers',
        )],
        'layout': {
            'height': 225,
            'margin': {'l': 50, 'b': 30, 'r': 10, 't': 10},
            'annotations': [{
                'x': 0, 'y': 0.85, 'xanchor': 'left', 'yanchor': 'bottom',
                'xref': 'paper', 'yref': 'paper', 'showarrow': False,
                'align': 'left', 'bgcolor': 'rgba(255, 255, 255, 0.5)',
                'text': title
            }],
            'yaxis': {'type': 'linear', 'title': column},
            'xaxis': {'showgrid': False}
        }
    } 
Example #12
Source File: components.py    From webmc3 with Apache License 2.0 7 votes vote down vote up
def lines_figure(trace_info, varname):
    x = np.arange(len(trace_info))

    return {
        'data': [
            go.Scatter(
                x=x, y=y,
                name="Chain {}".format(chain_ix)
            )
            for chain_ix, y in enumerate(
                trace_info.get_values(varname, combine=False)
            )
        ],
        'layout': go.Layout(
            yaxis={'title': "Sample value"},
            showlegend=False
        )
    } 
Example #13
Source File: viz.py    From ConvLab with MIT License 7 votes vote down vote up
def plot_mean_sr(sr_list, time_sr, title, y_title, x_title):
    '''Plot a list of series using its mean, with error bar using std'''
    mean_sr, std_sr = util.calc_srs_mean_std(sr_list)
    max_sr = mean_sr + std_sr
    min_sr = mean_sr - std_sr
    max_y = max_sr.tolist()
    min_y = min_sr.tolist()
    x = time_sr.tolist()
    color = get_palette(1)[0]
    main_trace = go.Scatter(
        x=x, y=mean_sr, mode='lines', showlegend=False,
        line={'color': color, 'width': 1},
    )
    envelope_trace = go.Scatter(
        x=x + x[::-1], y=max_y + min_y[::-1], showlegend=False,
        line={'color': 'rgba(0, 0, 0, 0)'},
        fill='tozerox', fillcolor=lower_opacity(color, 0.2),
    )
    data = [main_trace, envelope_trace]
    layout = create_layout(title=title, y_title=y_title, x_title=x_title)
    fig = go.Figure(data, layout)
    return fig 
Example #14
Source File: test_plotly.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_plotly_autosize(document, comm):
    trace = go.Scatter(x=[0, 1], y=[2, 3])
    
    pane = Plotly(dict(data=[trace], layout={'autosize': True}))

    model = pane.get_root(document, comm=comm)
    model.sizing_mode == 'stretch_both'

    pane.object['layout']['autosize'] = False
    pane.param.trigger('object')
    model.sizing_mode == 'fixed'

    pane._cleanup(model)
    
    pane = Plotly(dict(data=[trace], layout={'autosize': True}), sizing_mode='fixed')
    model = pane.get_root(document, comm=comm)
    model.sizing_mode == 'fixed'

    pane._cleanup(model) 
Example #15
Source File: test.py    From cups-rl with MIT License 6 votes vote down vote up
def _plot_line(xs, ys_population, title, path=''):
    """ Plots min, max and mean + standard deviation bars of a population over time """
    max_colour, mean_colour, std_colour, transparent = 'rgb(0, 132, 180)', 'rgb(0, 172, 237)', \
                                                       'rgba(29, 202, 255, 0.2)', 'rgba(0, 0, 0, 0)'

    ys = torch.tensor(ys_population, dtype=torch.float32)
    ys_min, ys_max, ys_mean, ys_std = ys.min(1)[0].squeeze(), ys.max(1)[0].squeeze(), \
                                      ys.mean(1).squeeze(), ys.std(1).squeeze()
    ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

    trace_max = Scatter(x=xs, y=ys_max.numpy(),
                        line=Line(color=max_colour, dash='dash'), name='Max')
    trace_upper = Scatter(x=xs, y=ys_upper.numpy(),
                          line=Line(color=transparent), name='+1 Std. Dev.', showlegend=False)
    trace_mean = Scatter(x=xs, y=ys_mean.numpy(), fill='tonexty', fillcolor=std_colour,
                         line=Line(color=mean_colour), name='Mean')
    trace_lower = Scatter(x=xs, y=ys_lower.numpy(), fill='tonexty', fillcolor=std_colour,
                          line=Line(color=transparent), name='-1 Std. Dev.', showlegend=False)
    trace_min = Scatter(x=xs, y=ys_min.numpy(),
                        line=Line(color=max_colour, dash='dash'), name='Min')

    plotly.offline.plot({
      'data': [trace_upper, trace_mean, trace_lower, trace_min, trace_max],
      'layout': dict(title=title, xaxis={'title': 'Step'}, yaxis={'title': title})
    }, filename=os.path.join(path, title + '.html'), auto_open=False) 
Example #16
Source File: plot.py    From sound_field_analysis-py with MIT License 6 votes vote down vote up
def prepare_2D_traces(data, viz_type, fs, line_names):
    data = _np.atleast_2d(data)
    N, L = data.shape

    x = prepare_2D_x(L, viz_type, fs)

    traces = [None] * N

    for k in range(0, N):
        y = data[k]
        traces[k] = go.Scatter(x=x, y=y if viz_type == 'TIME' else 20 * _np.log10(_np.abs(y)))
        try:
            traces[k].name = line_names[k]
        except (TypeError, IndentationError):
            pass

    return traces 
Example #17
Source File: rad_est_utils.py    From megaman with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plot_singular_values_versus_radius(singular_values, rad_search_space, start_idx, end_idx):
    all_trace = []
    singular_gap = -np.diff(singular_values,axis=1)
    for idx, sing in enumerate(singular_values.T):
        singular_line = go.Scatter(
            x=rad_search_space, y=sing, name='{} singular value'.format(ordinal(idx+1))
        )
        if idx <= 2:
            singular_line['text'] = [ 'Singular gap: {:.2f}'.format(singular_gap[rid, idx]) for rid in range(50) ]
        if idx > 3:
            singular_line['hoverinfo'] = 'none'
        all_trace.append(singular_line)
        if idx == 2:
            # HACK: just specify the color manually, need to generate each later.
            all_trace.append(go.Scatter(
                x=rad_search_space[start_idx:end_idx], y=singular_values[start_idx:end_idx,2],
                mode='lines',marker=dict(color='green'),
                showlegend=False, hoverinfo='none'
            ))
            all_trace.append(go.Scatter(
                x=rad_search_space[start_idx:end_idx], y=singular_values[start_idx:end_idx,1],
                fill='tonexty', mode='none', showlegend=False, hoverinfo='none'
            ))
    return all_trace 
Example #18
Source File: plot_plotly.py    From lantern with Apache License 2.0 6 votes vote down vote up
def scatter(self, data, color=None, x=None, y=None, y_axis='left', subplot=False, **kwargs):
        # Scatter all
        for i, col in enumerate(data):
            if i == 0:
                continue  # don't scatter against self
            x = data.columns[0]
            y = data.columns[i]
            c = get_color(i, col, color)
            fig = go.Figure(data=[go.Scatter(
                            x=data[x],
                            y=data[y],
                            mode='markers',
                            marker={'color': c},
                            name='%s vs %s' % (x, y),
                            **kwargs)])
            self.figures.append((col, fig, y_axis, c)) 
Example #19
Source File: plotly_apps.py    From django-plotly-dash with MIT License 5 votes vote down vote up
def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
    'Build a timeseries from the internal state'

    cache_key = _get_cache_key(state_uid)
    state = cache.get(cache_key)

    # If nothing in cache, prepopulate
    if not state:
        state = {}

    colour_series = {}

    colors = {'red':'#FF0000',
              'blue':'#0000FF',
              'green':'#00FF00',
              'yellow': '#FFFF00',
              'cyan': '#00FFFF',
              'magenta': '#FF00FF',
              'black' : '#000000',
             }

    for colour, values in state.items():
        timestamps = [datetime.fromtimestamp(int(0.001*ts)) for _, ts, _ in values if ts > 0]
        #users = [user for user, ts, _ in values if ts > 0]
        levels = [level for _, ts, level in values if ts > 0]
        if colour in colors:
            colour_series[colour] = pd.Series(levels, index=timestamps).groupby(level=0).first()

    df = pd.DataFrame(colour_series).fillna(method="ffill").reset_index()[-25:]

    traces = [go.Scatter(y=df[colour],
                         x=df['index'],
                         name=colour,
                         line=dict(color=colors.get(colour, '#000000')),
                        ) for colour in colour_series]

    return {'data':traces,
            #'layout': go.Layout
           } 
Example #20
Source File: test_plotly.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_plotly_pane_numpy_to_cds_traces(document, comm):
    trace = go.Scatter(x=np.array([1, 2]), y=np.array([2, 3]))
    pane = Plotly({'data': [trace], 'layout': {'width': 350}})

    # Create pane
    model = pane.get_root(document, comm=comm)
    assert isinstance(model, PlotlyPlot)
    assert len(model.data) == 1
    assert model.data[0]['type'] == 'scatter'
    assert 'x' not in model.data[0]
    assert 'y' not in model.data[0]
    assert model.layout == {'width': 350}
    assert len(model.data_sources) == 1
    cds = model.data_sources[0]
    assert np.array_equal(cds.data['x'][0], np.array([1, 2]))
    assert np.array_equal(cds.data['y'][0], np.array([2, 3]))

    # Replace Pane.object
    new_trace = [go.Scatter(x=np.array([5, 6]), y=np.array([6, 7])),
                 go.Bar(x=np.array([2, 3]), y=np.array([4, 5]))]
    pane.object = {'data': new_trace, 'layout': {'width': 350}}
    assert len(model.data) == 2
    assert model.data[0]['type'] == 'scatter'
    assert 'x' not in model.data[0]
    assert 'y' not in model.data[0]
    assert model.data[1]['type'] == 'bar'
    assert 'x' not in model.data[1]
    assert 'y' not in model.data[1]
    assert model.layout == {'width': 350}
    assert len(model.data_sources) == 2
    cds = model.data_sources[0]
    assert np.array_equal(cds.data['x'][0], np.array([5, 6]))
    assert np.array_equal(cds.data['y'][0], np.array([6, 7]))
    cds2 = model.data_sources[1]
    assert np.array_equal(cds2.data['x'][0], np.array([2, 3]))
    assert np.array_equal(cds2.data['y'][0], np.array([4, 5]))

    # Cleanup
    pane._cleanup(model)
    assert pane._models == {} 
Example #21
Source File: engine_plotly.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def getScatterGOs(self):
        for dataset in self.getDatasets():
            yield Scatter(
                x = dataset['x'],
                y = dataset['y'],
                **self.getArgsForDataset(dataset)
            ) 
Example #22
Source File: test_plotly.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_plotly_pane_single_trace(document, comm):
    trace = go.Scatter(x=[0, 1], y=[2, 3], uid='Test')
    pane = Plotly({'data': [trace], 'layout': {'width': 350}})

    # Create pane
    model = pane.get_root(document, comm=comm)
    assert isinstance(model, PlotlyPlot)
    assert pane._models[model.ref['id']][0] is model
    assert len(model.data) == 1
    assert model.data[0]['type'] == 'scatter'
    assert model.data[0]['x'] == [0, 1]
    assert model.data[0]['y'] == [2, 3]
    assert model.layout == {'width': 350}
    assert len(model.data_sources) == 1
    assert model.data_sources[0].data == {}

    # Replace Pane.object
    new_trace = go.Bar(x=[2, 3], y=[4, 5])
    pane.object = {'data': new_trace, 'layout': {'width': 350}}
    assert len(model.data) == 1
    assert model.data[0]['type'] == 'bar'
    assert model.data[0]['x'] == [2, 3]
    assert model.data[0]['y'] == [4, 5]
    assert model.layout == {'width': 350}
    assert len(model.data_sources) == 1
    assert model.data_sources[0].data == {}
    assert pane._models[model.ref['id']][0] is model

    # Cleanup
    pane._cleanup(model)
    assert pane._models == {} 
Example #23
Source File: scatter.py    From DataPlotly with GNU General Public License v2.0 5 votes vote down vote up
def name():
        return PlotType.tr('Scatter Plot') 
Example #24
Source File: figures.py    From dash-svm with MIT License 5 votes vote down vote up
def serve_roc_curve(model,
                    X_test,
                    y_test):
    decision_test = model.decision_function(X_test)
    fpr, tpr, threshold = metrics.roc_curve(y_test, decision_test)

    # AUC Score
    auc_score = metrics.roc_auc_score(y_true=y_test, y_score=decision_test)

    trace0 = go.Scatter(
        x=fpr,
        y=tpr,
        mode='lines',
        name='Test Data',
    )

    layout = go.Layout(
        title=f'ROC Curve (AUC = {auc_score:.3f})',
        xaxis=dict(
            title='False Positive Rate'
        ),
        yaxis=dict(
            title='True Positive Rate'
        ),
        legend=dict(x=0, y=1.05, orientation="h"),
        margin=dict(l=50, r=10, t=55, b=40),
    )

    data = [trace0]
    figure = go.Figure(data=data, layout=layout)

    return figure 
Example #25
Source File: add_remove_points.py    From dash-regression with MIT License 5 votes vote down vote up
def func(custom_data_storage):
    data = json.loads(custom_data_storage)

    trace0 = go.Contour(
        x=np.linspace(0, 10, 200),
        y=np.linspace(0, 10, 200),
        z=np.ones(shape=(200, 200)),
        showscale=False,
        hoverinfo='none',
        contours=dict(coloring='lines'),
    )
    trace1 = go.Scatter(
        x=data['train_X'],
        y=data['train_y'],
        mode='markers',
        name='Training'
    )
    trace2 = go.Scatter(
        x=data['test_X'],
        y=data['test_y'],
        mode='markers',
        name='Training'
    )

    data = [trace0, trace1, trace2]
    figure = go.Figure(data=data)
    return figure 
Example #26
Source File: pycoQC_plot.py    From pycoQC with GNU General Public License v3.0 5 votes vote down vote up
def __2D_density_plot (self,
        x_field_name, y_field_name, x_lab, y_lab, x_scale, y_scale, x_nbins, y_nbins,
        colorscale, smooth_sigma, width, height, plot_title):
        """Private function generating density plots for all 2D distribution functions"""
        self.logger.info ("\t\tComputing plot")

        # Prepare all data
        lab1, dd1 = self.__2D_density_data ("all", x_field_name, y_field_name, x_nbins, y_nbins, x_scale, y_scale, smooth_sigma)
        lab2, dd2 = self.__2D_density_data ("pass", x_field_name, y_field_name, x_nbins, y_nbins, x_scale, y_scale, smooth_sigma)

        # Plot initial data
        data = [
            go.Contour (x=dd1["x"][0], y=dd1["y"][0], z=dd1["z"][0], contours=dd1["contours"][0],
                name="Density", hoverinfo="name+x+y", colorscale=colorscale, showlegend=True, connectgaps=True, line={"width":0}),
            go.Scatter (x=dd1["x"][1], y=dd1["y"][1],
                mode='markers', name='Median', hoverinfo="name+x+y", marker={"size":12,"color":'black', "symbol":"x"})]

        # Create update buttons
        updatemenus = [
            dict (type="buttons", active=0, x=-0.2, y=0, xanchor='left', yanchor='bottom', buttons = [
                dict (label=lab1, method='restyle', args=[dd1]),
                dict (label=lab2, method='restyle', args=[dd2])])]

        # tweak plot layout
        layout = go.Layout (
            hovermode = "closest",
            plot_bgcolor="whitesmoke",
            legend = {"x":-0.2, "y":1,"xanchor":'left',"yanchor":'top'},
            updatemenus = updatemenus,
            width = width,
            height = height,
            title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"},
            xaxis = {"title":x_lab, "showgrid":True, "zeroline":False, "showline":True, "type":x_scale},
            yaxis = {"title":y_lab, "showgrid":True, "zeroline":False, "showline":True, "type":y_scale})

        return go.Figure (data=data, layout=layout) 
Example #27
Source File: pycoQC_plot.py    From pycoQC with GNU General Public License v3.0 5 votes vote down vote up
def __1D_density_plot (self, field_name, plot_title, x_lab, color, x_scale, nbins, smooth_sigma, width, height):
        """Private function generating density plots for all 1D distribution functions"""
        self.logger.info ("\t\tComputing plot")

        # Prepare all data
        lab1, dd1, ld1 = self.__1D_density_data ("all", field_name, x_scale, nbins, smooth_sigma)
        lab2, dd2, ld2 = self.__1D_density_data ("pass" ,field_name, x_scale, nbins, smooth_sigma)

        # Plot initial data
        common = {
            "mode": "lines+text",
            "hoverinfo": "skip",
            "textposition": 'top center',
            "line":  {'color':'gray','width':1,'dash': 'dot'}}
        data = [
            go.Scatter (x=dd1["x"][0], y=dd1["y"][0], name=dd1["name"][0], fill='tozeroy', fillcolor=color, mode='none', showlegend=True),
            go.Scatter (x=dd1["x"][1], y=dd1["y"][1], name=dd1["name"][1], text=dd1["text"][1], **common),
            go.Scatter (x=dd1["x"][2], y=dd1["y"][2], name=dd1["name"][2], text=dd1["text"][2], **common),
            go.Scatter (x=dd1["x"][3], y=dd1["y"][3], name=dd1["name"][3], text=dd1["text"][3], **common),
            go.Scatter (x=dd1["x"][4], y=dd1["y"][4], name=dd1["name"][4], text=dd1["text"][4], **common),
            go.Scatter (x=dd1["x"][5], y=dd1["y"][5], name=dd1["name"][5], text=dd1["text"][5], **common)]

        # Create update buttons
        updatemenus = [
            dict (type="buttons", active=0, x=-0.2, y=0, xanchor='left', yanchor='bottom', buttons = [
                dict (label=lab1, method='update', args=[dd1, ld1]),
                dict (label=lab2, method='update', args=[dd2, ld2])])]

        # tweak plot layout
        layout = go.Layout (
            hovermode = "closest",
            plot_bgcolor="whitesmoke",
            legend = {"x":-0.2, "y":1,"xanchor":'left',"yanchor":'top'},
            updatemenus = updatemenus,
            width = width,
            height = height,
            title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"},
            xaxis = {"title":x_lab, "type":x_scale, "zeroline":False, "showline":True},
            yaxis = {"title":"Read density", "zeroline":False, "showline":True, "fixedrange":True, "range":ld1["yaxis.range"]})

        return go.Figure (data=data, layout=layout) 
Example #28
Source File: HydroSEDPlots.py    From WMF with GNU General Public License v3.0 5 votes vote down vote up
def Plot_Storages(self, StoragePath, PathFigure):
        '''Hace un plot del storage en el periodo de simulacion'''
        #Lee los datos 
        Data = pd.read_csv(StoragePath, skiprows=4, index_col=6, parse_dates=True)
        #Hace la figura
        fig = tools.make_subplots(rows=5, cols=1)
        for c,key in enumerate(Data.columns.values[1:].tolist()):
            trace1 = go.Scatter(
                x = Data.index.to_pydatetime(),
                y = Data[key].values,
                name = key,
                line = {'width':3},
                fill='tozeroy',
            )
            fig.append_trace(trace1, c+1, 1)
        fig['layout'].update(height=600, width=600,
            showlegend = False,
            yaxis=dict(title='Estado [mm]',),
            margin=dict(
                l=50,
                r=50,
                b=50,
                t=50,
                pad=4
            ))
        plot(fig,filename=PathFigure, auto_open = False) 
Example #29
Source File: HydroSEDPlots.py    From WMF with GNU General Public License v3.0 5 votes vote down vote up
def Plot_CDC_caudal(self,pathFigure,dfQobs,dfQsim):
        Qs=np.sort(np.array(dfQsim.values))
        Qo=np.sort(np.array(dfQobs.values))
        porcen_s=[]
        porcen_o=[]
        
        for i in range(len(Qo)):
            porcen_o.append((len(Qo[Qo>Qo[i]]))/float(len(Qo))*100)
        for i in range(len(Qs)):
            porcen_s.append((len(Qs[Qs>Qs[i]]))/float(len(Qs))*100)
            
        trace_high = go.Scatter(
                x=porcen_s,
                y=Qs,
                name = "Q simulado",
                line = dict(color = 'red'),
                opacity = 0.8)

        trace_low = go.Scatter(
                        x=porcen_o,
                        y=Qo,
                        name = "Q observado",
                        line = dict(color = 'blue'),
                        opacity = 0.8)

        data = [trace_high,trace_low]

        layout = dict(showlegend = False,
            width=500,
            height=400,
            xaxis = dict(
                title='Porcentaje de Excedencia'),
            yaxis=dict(
                title='$Caudal [m^3/s]$')
    
        )
        fig = dict(data=data, layout=layout)
        #Guarda el html
        plot(fig,filename=pathFigure, auto_open = False) 
Example #30
Source File: visuals.py    From python-esppy with Apache License 2.0 5 votes vote down vote up
def createContent(self):
        values = self.getValues("y")

        self._data = []

        width = self.getOpt("line_width",2)
        shape = "linear"
        if self.getOpt("curved",False):
            shape = "spline"
        line = {"width":width,"shape":shape}

        fill = self.getOpt("fill",False)

        colors = self._visuals._colors.getFirst(len(values))

        mode = "lines"

        if fill:
            mode = "none"
        elif self.hasOpt("mode"):
            mode = self.getOpt("mode")

        for i,v in enumerate(values):
            if fill:
                if i == 0:
                    self._data.append(go.Scatter(x=[""],y=[0],name=v,mode=mode,fill="tozeroy",fillcolor=colors[i]))
                else:
                    self._data.append(go.Scatter(x=[""],y=[0],name=v,mode=mode,fill="tonexty",fillcolor=colors[i]))
            else:
                line["color"] = colors[i]
                self._data.append(go.Scatter(x=[""],y=[0],name=v,mode=mode,line=line))