我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用plotly.graph_objs.Data()。
def plot_frame(dataframe, uname=None, api_key=None, mode='lines', line={}): try: import plotly.plotly as ply import plotly.tools as ptls from plotly.graph_objs import Scatter, Layout, Data, Figure except ImportError: raise InvalidOperationException("Please install the Python plotly bindings") if uname and api_key: ply.sign_in(uname, api_key) c1 = dataframe.ch1 c2 = dataframe.ch2 x = list(range(len(c1))) t1 = Scatter(x=x, y=c1, mode=mode, line=line) t2 = Scatter(x=x, y=c2, mode=mode, line=line) layout = Layout(title="Moku:Lab Frame Grab") data = Data([t1, t2]) fig = Figure(data=data, layout=layout) return ply.plot(fig)
def scatter_line_chart(df, y_title): """Generate a reproducible plotly scatter and line plot.""" if len(df.columns) == 3: x_axis, y_axis, factor = df.columns data = go.Data([ go.Scatter(x=sub[x_axis], y=sub[y_axis], name=key) for key, sub in df.groupby(factor, as_index=False, sort=False)]) else: x_axis, y_axis = df.columns data = go.Data([ go.Scatter(x=df[x_axis], y=df[y_axis])]) layout = go.Layout( width=650, height=500, xaxis=go.XAxis( title="Commit Hash" if x_axis == "commit_hash" else "Timestamp", tickangle=-45 if x_axis == "commit_hash" else 0 ), yaxis=go.YAxis( title=y_title ) ) return Markup(py.plot(go.Figure(data=data, layout=layout), **_DEFAULT_ARGS))
def _insert_headers(self, c, key, message): """Adds all headers to `headers`. WARNING: Data in this table does _not_ currently respect the self.anonymize setting. This is meant to be a raw record of all headers. """ for header, value in message.items(): c.execute('''INSERT INTO headers VALUES(?, ?, ?);''', (key, header, value.decode('utf-8'))) self.query_count += 1
def boolean_chart(df, y_title): """Generate a reproducible plotly scatter and line plot.""" if len(df.columns) == 3: x_axis, y_axis, factor = df.columns data = go.Data([ go.Scatter(x=sub[x_axis], y=sub[y_axis].astype(int), name=key) for key, sub in df.groupby(factor, as_index=False, sort=False)]) else: x_axis, y_axis = df.columns data = go.Data([ go.Scatter(x=df[x_axis], y=df[y_axis].astype(int))]) layout = go.Layout( width=650, height=500, xaxis=go.XAxis( title="Commit Hash" if x_axis == "commit_hash" else "Timestamp", tickangle=-45 if x_axis == "commit_hash" else 0 ), yaxis=go.YAxis( title=y_title, zeroline=False, tickmode="array", tickvals=[0, 1], ticktext=["No", "Yes"] ) ) return Markup(py.plot(go.Figure(data=data, layout=layout), **_DEFAULT_ARGS))
def _update_graph(map_style, region): dff = dataframe radius_multiplier = {'inner': 1.5, 'outer': 3} layout = go.Layout( title=metadata['title'], autosize=True, hovermode='closest', height=750, font=dict(family=theme['font-family']), margin=go.Margin(l=0, r=0, t=45, b=10), mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=regions[region]['lat'], lon=regions[region]['lon'], ), pitch=0, zoom=regions[region]['zoom'], style=map_style, ), ) data = go.Data([ # outer circles represent magnitude go.Scattermapbox( lat=dff['Latitude'], lon=dff['Longitude'], mode='markers', marker=go.Marker( size=dff['Magnitude'] * radius_multiplier['outer'], colorscale=colorscale_magnitude, color=dff['Magnitude'], opacity=1, ), text=dff['Text'], # hoverinfo='text', showlegend=False, ), # inner circles represent depth go.Scattermapbox( lat=dff['Latitude'], lon=dff['Longitude'], mode='markers', marker=go.Marker( size=dff['Magnitude'] * radius_multiplier['inner'], colorscale=colorscale_depth, color=dff['Depth'], opacity=1, ), # hovering behavior is already handled by outer circles hoverinfo='skip', showlegend=False ), ]) figure = go.Figure(data=data, layout=layout) return figure
def graph_creation(strategy, data, mae_, system_slug, symbol_slug, period, direction, bh_title): try: if not (strategy is None): strategy_ = strategy.loc[strategy != 0.0] x = strategy.loc[strategy != 0].index mae_ = mae_.loc[(mae_ != mae_.shift()) | (strategy != 0.0)] #graphs strategy_graph = go.Scatter(x=x, y=strategy_, mode="lines", \ name=T('Strategy'), line=dict(color=('rgb(205, 12, 24)'), width=6)) mae_graph = go.Scatter(x=x, y=mae_, mode="markers", \ name=T('Strategy MAE'), line=dict(color=('rgb(115,115,115,1)'), \ width=4, dash='dot')) if not (data is None): data_ = data.loc[strategy != 0.0] data_graph = go.Scatter(x=x, y=data_, mode="lines", name=bh_title, \ line=dict(color=('rgb(22, 96, 167)'), width=4, dash='dot')) title = "{0} on {1} {2} {3}".format(system_slug, symbol_slug, \ period, direction) #else: #title = "Portfolio {}".format(system_slug) if not (data is None): fig_data = go.Data([data_graph, strategy_graph, mae_graph], \ showgrid=True) else: fig_data = go.Data([strategy_graph, mae_graph], showgrid=True) layout = go.Layout(title=title, xaxis={'title':T('Dates')}, \ yaxis={'title':T('$')}, font=dict(family='Courier New, \ monospace', size=14, color='#7f7f7f') ) figure = go.Figure(data=fig_data, layout=layout) graph = opy.plot(figure, auto_open=False, output_type='div') else: graph = None return graph except Exception as e: #stck = inspect.stack() #msg='{0} by {1}: {2}'.format(stck[0][3], stck[1][3], e) #error_email(e=msg) return None
def auto_portfolio_page(request, **kwargs): try: broker_slug = kwargs['broker_slug'] broker_slug = force_text(broker_slug, encoding='utf-8', strings_only=True, errors='strict') except: return HttpResponseRedirect('/') broker = Brokers.objects.get(slug=broker_slug) filename = join(settings.DATA_PATH, 'portfolios', '{}_qndx'.format(broker.slug)) df = nonasy_df_multi_reader(filename=filename, limit=True) hist = list(df['LONG_PL'].loc[df['LONG_PL'] != 0]) hold_hist = list(df['DIFF'].loc[df['DIFF'] != 0]) stats = Stats.objects.get(symbol__symbol='AI50', period__period='1440', \ system__title='AI50', direction=1, broker=broker) hist_graph = hist_graph_creation(hist=hist, hold_hist=hold_hist) margin_data = go.Scatter(x=df.index, y=df.LONG_MARGIN, mode="lines", \ name=T('Margin'), line=dict(color=('rgb(205, 12, 24)'), width=2)) trades_data = go.Scatter(x=df.index, y=df.LONG_TRADES, mode="lines", \ name=T('Trades'), line=dict(color=('rgb(205, 12, 24)'), width=2)) pl_data = go.Scatter(x=df.index, y=df.LONG_PL_CUMSUM, mode="lines", \ name=T('Cumulative returns'), line=dict(color=('rgb(205, 12, 24)'), width=6)) mae_data = go.Scatter(x=df.index, y=df.LONG_MAE, mode="markers", \ name=T('MAE'), line=dict(color=('rgb(115,115,115,1)'), width=4, dash='dot')) margin_g = go.Data([margin_data], showgrid=True) trades_g = go.Data([trades_data], showgrid=True) main_g = go.Data([pl_data, mae_data], showgrid=True) main_layout = go.Layout(title='Autoportfolio Index 50 performance', xaxis={'title':T('Dates')}, \ yaxis={'title':T('$')}, font=dict(family='Courier New, \ monospace', size=14, color='#7f7f7f') ) margin_layout = go.Layout(title='Used margin over time', xaxis={'title':T('Dates')}, \ yaxis={'title':T('$')}, font=dict(family='Courier New, \ monospace', size=14, color='#7f7f7f') ) trades_layout = go.Layout(title='Trades over time', xaxis={'title':T('Dates')}, \ yaxis={'title':T('Count')}, font=dict(family='Courier New, \ monospace', size=14, color='#7f7f7f') ) margin_fig = go.Figure(data=margin_g, layout=margin_layout) trades_fig = go.Figure(data=trades_g, layout=trades_layout) main_fig = go.Figure(data=main_g, layout=main_layout) margin_graph = opy.plot(margin_fig, auto_open=False, output_type='div') trades_graph = opy.plot(trades_fig, auto_open=False, output_type='div') graph = opy.plot(main_fig, auto_open=False, output_type='div') return render(request, '{}/auto_portfolio.html'.format(settings.TEMPLATE_NAME), { 'graph': graph, 'hist_graph': hist_graph, 'stats': stats, 'autoportfolio': True, 'heatmap': stats.heatmap, 'margin_graph': margin_graph, 'trades_graph': trades_graph, 'yearly_img': stats.yearly_ret, 'broker': broker })
def plot(self, figure_or_data, validate=True): """Plot figure_or_data in the Plotly graph widget. Args: figure_or_data (dict, list, or plotly.graph_obj object): The standard Plotly graph object that describes Plotly graphs as used in `plotly.plotly.plot`. See examples of the figure_or_data in https://plot.ly/python/ Returns: None Example 1 - Graph a scatter plot:
from plotly.graph_objs import Scatter g = GraphWidget() g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])]) ``` Example 2 - Graph a scatter plot with a title: ``` from plotly.graph_objs import Scatter, Figure, Data fig = Figure( data = Data([ Scatter(x=[1, 2, 3], y=[20, 15, 13]) ]), layout = Layout(title='Experimental Data') ) g = GraphWidget() g.plot(fig) ``` Example 3 - Clear a graph widget ``` from plotly.graph_objs import Scatter, Figure g = GraphWidget() g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])]) # Now clear it g.plot({}) # alternatively, g.plot(Figure()) ``` """ if figure_or_data == {} or figure_or_data == Figure(): validate = False figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) message = { 'task': 'newPlot', 'data': figure.get('data', []), 'layout': figure.get('layout', {}), 'graphId': self._graphId } self._handle_outgoing_message(message)
```