我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用plotly.graph_objs.Scatter()。
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 prepare_2D_traces(data, viz_type=None, fs=None, line_names=None): 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): traces[k] = go.Scatter( x=x, y=data[k] ) try: traces[k].name = line_names[k] except TypeError: pass return traces
def _scatter(self, df, color=None, data_type=None, opacity=None, showscale=False, colorbar_title=None, text=None, customdata=None, name=None, **kwargs): cmin = None cmax = None if data_type is not None and 'expression'.startswith(data_type): cmin = 0.0 kwargs['marker'] = dict(color=color, cmin=cmin, cmax=cmax, colorscale='Viridis', opacity=opacity, showscale=showscale, colorbar=dict(thickness=20, title=colorbar_title, titleside='right')) scatter = go.Scatter(x=df[0], y=df[1], mode='markers', hoverinfo='text', text=text, customdata=customdata, name=name, **kwargs) return scatter
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)
def plot_line(xs, ys_population, filename, y_title=''): 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(xaxis={'title': 'Step'}, yaxis={'title': y_title}) }, filename=filename, auto_open=False)
def probabilitygraph(data, vec1, high, k=5, weightf=gaussian, ss=5.0): t1 = np.arange(0.0, high, 0.1) probs = np.array([probguess(data, vec1, v, v+0.1, k, weightf) for v in t1]) smoothed = [] for i in xrange(len(probs)): sv = 0.0 for j in xrange(len(probs)): dist = abs(i-j)*0.1 weight = gaussian(dist, sigma=ss) sv += weight*probs[j] smoothed.append(sv) smoothed = np.array(smoothed) data = go.Scatter(x=t1, y=smoothed) fig = go.Figure(data=[data]) py.plot(fig, filename='wineguess_smoothed')
def plot_traj(self, qt, **kwargs) : if self.vis_mode == '2D' : trajs = self.periodize_traj(qt) for traj in trajs : # (r,theta) -> (y,x) curve = go.Scatter(x = traj[:,1], y = traj[:,0], mode = 'lines', hoverinfo='none', **kwargs) self.current_axis.append(curve) elif self.vis_mode == '3D' : if type(qt[0]) is not list : qt = [qt] if self.upsample_trajs : qt = list( self.upsample(q) for q in qt ) traj = list( self.I(q = q) for q in qt ) separator = array([None]* 3).reshape((1,3)) traj = vstack( vstack((i, separator)) for i in traj ) curve = go.Scatter3d(x = traj[:,0], y = traj[:,1], z = traj[:,2], mode = 'lines', hoverinfo='none', **kwargs) self.current_axis.append(curve) # Vector field display
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)
def make_number_line(similar, group, df): # ''' # description: makes a scatter plot of most relevant courses can be grouped by group data # params: similar: list of tuples, where each tuple is a course name and its similarity score. # group: string, name of column containing group data # df: data frame where the row index is by course title and column name is the string group. contains the name of the group the course belongs to # returns: plotly figure # ''' titles, scores = zip(*similar) if group == None: y_axis = [0]*len(scores) layout = dict(yaxis = dict(visible = False), title = 'Similar Courses') else: y_axis = [df.loc[title][group] for title in titles] layout = dict(title = 'Similar Courses') trace = go.Scatter( x = scores, y= y_axis, mode = 'markers', text = titles) data = [trace] fig = go.Figure(data=data, layout = layout) return fig
def ml_plot_ROC(tpr_dict, fpr_dict, names, title=None, plot=True): color_list = ['rgb(244, 167, 66)', 'rgb(49,130,189)', 'rgb(244, 65, 86)','rgb(100, 201, 137)'] i = 0 list_plots = [] for name in names: list_plots.append(go.Scatter( x=fpr_dict[name], y=tpr_dict[name], mode='lines', name=name, marker = dict(color=color_list[i]) )) i += 1 layout = dict(title = "ROC Curve", xaxis = dict(title="False Positive Rate"), yaxis = dict(title="True Positive Rate"),) fig = dict(data=list_plots, layout=layout) if plot == True: iplot(fig, config={'showLink' : False, 'displaylogo' : False, 'modeBarButtonsToRemove' : ['sendDataToCloud']}) else: return fig
def ml_plot_learning_curve(train_scores, validation_scores): trace0 = go.Scatter( x = np.arange(10, 101, 10), y = train_scores, mode = 'lines+markers', name = 'Training Score' ) trace1 = go.Scatter( x = np.arange(10, 101, 10), y = validation_scores, mode = 'lines+markers', name = 'Cross-Validation Scores' ) data=[trace0, trace1] iplot(data)
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)
def scatter_plot(xs, ys=None, xlabel='', ylabel='', title='', lines=False, marker=dict()): layout = Layout( title=title, xaxis=dict(title=xlabel), yaxis=dict(title=ylabel) ) if ys is None: ys = xs xs = list(range(len(xs))) data = [ Scatter(x=xs, y=ys, mode='lines' if lines else 'markers', marker=marker) ] figure = Figure(data=data, layout=layout) plotly.offline.plot(figure, filename=title + '.html')
def get_metric_apache_cpu_load(self, mess, args): res = self.es_request_metric('apache.status.cpu.load') if res['hits']['hits']: xdata = list(); ydata = list(); for hit in res['hits']['hits']: xdata.append(hit['_source']['@timestamp']) ydata.append(hit['_source']['apache']['status']['cpu']['load']) img_name = "apache_status_cpu_load_" + str(uuid.uuid4())+".html" plot([go.Scatter(x=xdata, y=ydata)], filename='/var/www/html/'+img_name,image='jpeg') #return 'Click below link for metric data\n' + HOST_URL + '/' + img_name self.send_card(title='Metric Graph link', body='Click above link for metric data\n', image="https://raw.githubusercontent.com/debojitkakoti/atraey/master/atraey-logo.png", link=HOST_URL + '/' + img_name, color='red', in_reply_to=mess) else: return "Oops no enough data to measure apache cpu load"
def get_metric_apache_status_kb(self, mess, args): res = self.es_request_metric('apache.status.total_kbytes') if res['hits']['hits']: xdata = list(); ydata = list(); for hit in res['hits']['hits']: xdata.append(hit['_source']['@timestamp']) ydata.append(hit['_source']['apache']['status']['total_kbytes']) img_name = "apache_status_kb_" + str(uuid.uuid4())+".html" plot([go.Scatter(x=xdata, y=ydata)], filename='/var/www/html/'+img_name,image='jpeg') #return 'Click below link for metric data\n' + HOST_URL + '/' + img_name self.send_card(title='Metric Graph link', body='Click above link for metric data\n', image="https://raw.githubusercontent.com/debojitkakoti/atraey/master/atraey-logo.png", link=HOST_URL + '/' + img_name, color='red', in_reply_to=mess) else: return "Oops no enough data to measure apache status kbytes served"
def get_metric_apache_status_accesses(self, mess, args): res = self.es_request_metric('apache.status.total_accesses') if res['hits']['hits']: xdata = list(); ydata = list(); for hit in res['hits']['hits']: xdata.append(hit['_source']['@timestamp']) ydata.append(hit['_source']['apache']['status']['total_accesses']) img_name = "apache_status_accesses_" + str(uuid.uuid4())+".html" plot([go.Scatter(x=xdata, y=ydata)], filename='/var/www/html/'+img_name,image='jpeg') #return 'Click below link for metric data\n' + HOST_URL + '/' + img_name self.send_card(title='Metric Graph link', body='Click above link for metric data\n', image="https://raw.githubusercontent.com/debojitkakoti/atraey/master/atraey-logo.png", link=HOST_URL + '/' + img_name, color='red', in_reply_to=mess) else: return "Oops no enough data to measure apache status total accesses"
def get_metric_apache_status_requests(self, mess, args): res = self.es_request_metric('apache.status.requests_per_sec') if res['hits']['hits']: xdata = list(); ydata = list(); for hit in res['hits']['hits']: xdata.append(hit['_source']['@timestamp']) ydata.append(hit['_source']['apache']['status']['requests_per_sec']) img_name = "apache_status_requests_" + str(uuid.uuid4())+".html" plot([go.Scatter(x=xdata, y=ydata)], filename='/var/www/html/'+img_name,image='jpeg') #return 'Click below link for metric data\n' + HOST_URL + '/' + img_name self.send_card(title='Metric Graph link', body='Click above link for metric data\n', image="https://raw.githubusercontent.com/debojitkakoti/atraey/master/atraey-logo.png", link=HOST_URL + '/' + img_name, color='red', in_reply_to=mess) else: return "Oops no enough data to measure apache status requests per second"
def get_metric_apache_status_bps(self, mess, args): res = self.es_request_metric('apache.status.bytes_per_sec') if res['hits']['hits']: xdata = list(); ydata = list(); for hit in res['hits']['hits']: xdata.append(hit['_source']['@timestamp']) ydata.append(hit['_source']['apache']['status']['bytes_per_sec']) img_name = "apache_status_bps_" + str(uuid.uuid4())+".html" plot([go.Scatter(x=xdata, y=ydata)], filename='/var/www/html/'+img_name,image='jpeg') #return 'Click below link for metric data\n' + HOST_URL + '/' + img_name self.send_card(title='Metric Graph link', body='Click above link for metric data\n', image="https://raw.githubusercontent.com/debojitkakoti/atraey/master/atraey-logo.png", link=HOST_URL + '/' + img_name, color='red', in_reply_to=mess) else: return "Oops no enough data to measure apache status bytes per second"
def get_example_plot_html(number_of_points=30): import plotly.offline from plotly.graph_objs import Scatter, Layout, Bar, Margin data_x = [] data_y = [] for i in range(0, number_of_points): data_x.append(i) data_y.append(random.randint(-10, 10)) return plotly.offline.plot( figure_or_data={ "data": [Scatter(x=data_x, y=data_y)], "layout": Layout(title="Plot Title") }, show_link=False, output_type='div', include_plotlyjs=False, auto_open=False, )
def create_data(self): data = [] for i in range(0, len(self.party_labels)): bin_values, bin_edges = bin_datetimes(self.party_kamervragen_dates[i], range_years=7, bin_size_days=30) x, y_moving_avg = movingaverage_from_histogram(bin_values, bin_edges, window=3) x_new = [] for value in x: date = datetime.datetime.fromtimestamp(value / 1000.0) x_new.append(date) moving_average_scatter = Scatter( x=x_new, y=y_moving_avg, mode='lines', name=self.party_labels[i], line=dict(shape='spline'), ) data.append(moving_average_scatter) return data
def create_data(self): data = [] for i in range(0, len(self.party_labels)): weights = [] for seat in self.party_seats[i]: weights.append(1 / seat) bin_values, bin_edges = bin_datetimes(self.party_kamervragen_dates[i], range_years=7, bin_size_days=30, weights=weights) x, y_moving_avg = movingaverage_from_histogram(bin_values, bin_edges, window=3) x_new = [] for value in x: date = datetime.datetime.fromtimestamp(value / 1000.0) x_new.append(date) moving_average_scatter = Scatter( x=x_new, y=y_moving_avg, mode='lines', name=self.party_labels[i], line=dict(shape='spline'), ) data.append(moving_average_scatter) return data
def corrConvergencePlot(self, simId, scenario, resultName): df = self.getCorrByTrials(simId, scenario, resultName) params = list(df['paramName'].unique()) traces = [] count = max(df['count']) # create a trace for each parameter for paramName in params: paramData = df.query('paramName == "%s"' % paramName) trace = go.Scatter(x=list(paramData['count']), y=list(paramData['spearman']), name=paramName, mode='lines') traces.append(trace) # Round up to nearest integral value of CORR_STEP endX = count + (CORR_STEP - count % CORR_STEP) layout = updateStyle('Plot', title='Correlation Convergence for %s' % resultName, xaxis=dict(range=[CORR_STEP, endX]), margin=updateStyle('PlotMargin', l=40)) figure = dict(data=traces, layout=layout) return figure
def process(self, msg): """`plot: hovno`""" params = msg.extract_parameters(self.parameters, ) from bs4 import BeautifulSoup from yahoo_finance import Share import plotly.plotly as py import plotly.graph_objs as go from dateutil.parser import parse yahoo = Share(params['finance']) history = yahoo.get_historical(params['date-from'], params['date-to']) x = [parse(d['Date']) for d in history] data = [go.Scatter(x=x, y=[d['Close'] for d in history])] f = py.iplot(data) soup = BeautifulSoup(f.data, 'html.parser').find_all("iframe")[0] msg.reply(soup.get("src"))
def create_scatter_plot(origin: int): """ Returns a Scatter plot for data that has the specified region of origin :param origin: The region of origin (1, 2 or 3) for which to create a Scatter plot :return: The Scatter plot object for that region """ df_slice = df.query('origin == {}'.format(origin)) return go.Scatter( x=df_slice['hp'], y=df_slice['mpg'], mode='markers', name=origin ) # Create a list of Scatter plots for each region
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 build(self, x, y, title=""): div = plotly.offline.plot({ "data": [Scatter(x=x, y=y)], "layout": Layout(title=title, # xaxis=dict(range=[4200, 5300]), # yaxis=dict(range=[0.5, 2]), ) }, output_type='div', include_plotlyjs=False) return div
def callbacks(self, app): @app.callback( Output(self.ID, 'figure'), [Input(self.SUBSET_ID, 'value'), # Input(SmushedPlot.SELECTED_GENE_ID, 'value'), # Input(SmushedPlot.SELECTED_METADATA_ID, 'value') ]) def update_reads_vs_genes(group_name, selected_gene=None, selected_metadata=None): """When a group is selected, update the reads v genes scatter""" group_barcodes = self._get_dropdown_barcodes(group_name) group_metadata_subset = self.cell_metadata.loc[group_barcodes] x = group_metadata_subset[self.n_molecules_col] y = group_metadata_subset[self.n_genes_col] return { "data": [go.Scatter(x=x, y=y, mode='markers', hoverinfo='text', text=group_metadata_subset.index, customdata=group_metadata_subset.index)], "layout": go.Layout(xaxis={'title': 'Reads per cell'}, yaxis={'title': "Genes per cell"}, margin={'b': 40, 't': 10, 'r': 0}, hovermode='closest', dragmode='select'), }
def plot_labelprop(coords, communities, filename=None, title=''): scatters = [] n_communities = len(np.unique(communities)) scatter = go.Scatter(x=coords[0], y=coords[1], mode='markers', name=communities, hoverinfo='text', text=communities, marker=dict(color=communities, cmin=0.0, cmax=n_communities - 1, colorscale='Viridis' )) fig = { 'data': [scatter], "layout": go.Layout(title=f'Graph layout of cell type clusters: {title}', xaxis={'showticklabels': False}, yaxis={'showticklabels': False}, hovermode='closest', dragmode='select', show_legend=True) } if filename is None: plotly.offline.iplot(fig) else: plotly.offline.plot(fig, filename=filename, image='png')
def thread_sizes(self): """Returns a graph showing thread size information. A "thread" must consist of more than one email. """ c = self.conn.cursor() c.execute('''SELECT COUNT(message_key) AS message_count FROM messages WHERE gmail_labels NOT LIKE '%Chat%' GROUP BY gmail_thread_id HAVING message_count > 1;''') counts = {} for row in c.fetchall(): if row[0] not in counts: counts[row[0]] = 0 counts[row[0]] += 1 data = dict( x=counts.keys(), y=counts.values(), name='Emails in thread', mode='lines+markers', marker=dict( color=self.config.get('color', 'primary'), ), ) layout_args = plotly_default_layout_options() layout_args['title'] = 'Thread Sizes' layout_args['xaxis']['title'] = 'Number of messages' layout_args['yaxis']['title'] = 'Number of threads' layout = pgo.Layout(**layout_args) return plotly_output(pgo.Figure(data=[pgo.Scatter(**data)], layout=layout))
def talk_times(self): """Returns a plotly graph showing chat habits by hour of the day (UTC). """ c = self.conn.cursor() c.execute('''SELECT strftime('%H', `date`) AS hour, COUNT(message_key) AS talk_messages FROM messages WHERE gmail_labels LIKE '%Chat%' GROUP BY hour ORDER BY hour ASC;''') data = OrderedDict() for row in c.fetchall(): data[row[0]] = row[1] total_messages = sum(data.values()) percentages = OrderedDict() for hour in data.keys(): percentages[hour] = str(round(float(data[hour])/float(total_messages) * 100, 2)) + '%' data_args = dict( x=data.keys(), y=data.values(), text=percentages.values(), name='Chat messages', marker=dict( color=self.config.get('color', 'primary') ), fill='tozeroy', ) layout_args = plotly_default_layout_options() layout_args['title'] = 'Chat Times (UTC)' layout_args['xaxis']['title'] = 'Hour of day (UTC)' layout_args['yaxis']['title'] = 'Chat messages' trace = pgo.Scatter(**data_args) layout = pgo.Layout(**layout_args) return plotly_output(pgo.Figure(data=[trace], layout=layout))
def GenScatter(data): return Scatter(x=data[0], y=data[1])
def cumulativegraph(data,vec1,high,k=5,weightf=gaussian): t1 = np.arange(0.0, high, 0.1) cprob = np.array([probguess(data, vec1, 0, v, k, weightf) for v in t1]) data = go.Scatter(x=t1, y=cprob) fig = go.Figure(data=[data]) py.plot(fig, filename='wineguess')
def costs_curve(self) : values = self.cost_values s = unique(values) values = values - s[0] + .5 * (s[1] - s[0]) # Create a trace trace = go.Scatter( x = arange(len(values))+1, y = array(values), name = 'Cost excess' ) mark = go.Scatter( x = array([1]), y = array([values[0]]), marker = dict( color = "rgb(0, 0, 128)", size = 15 ), name = 'Current value', mode = 'markers' ) data = [trace, mark] layout = go.Layout( title='Cost excess across iterations', width=800, height=800, legend = dict( x = .8, y = 1), #xaxis = dict(range = [-3,3]), #yaxis = dict(range = [-3,3]) yaxis=dict( type='log', autorange=True ) ) return my_iplot(go.Figure(data=data, layout=layout)) + (values,)
def plot_traj(self, qts, **kwargs) : "Trajectory display. qt can be an array of coordinates, or a list of such arrays." if type(qts[0]) is not list : qts = [qts] points = [] separator = array([None]* self.dimension).reshape((1,self.dimension)) for qt in qts : for curve in qt : points.append( curve.to_plot() ) points.append( separator ) points = vstack(points) points = go.Scatter(x = array(points[:,0]), y = array(points[:,1]), mode = 'lines', hoverinfo='name', **kwargs) self.current_axis.append(points)
def marker(self, q, **kwargs) : """Marker field display""" if type(q) is not list : q = [q] points = [] separator = array([None]* self.dimension) for curve in q : points.append( curve.to_plot() ) points.append( separator ) points = vstack(points) points = go.Scatter(x = array(points[:,0]), y = array(points[:,1]), mode = 'lines', hoverinfo='name', **kwargs) self.current_axis.append(points)
def interactive_marker(self, q, **kwargs) : """Marker field display""" if type(q) is not list : q = [q] points = [] separator = np.array([None]* self.dimension) for curve in q : points.append( self.to_plot(curve) ) points.append( separator ) points = np.vstack(points) points = go.Scatter(x = np.array(points[:,0]), y = np.array(points[:,1]), mode = 'lines', hoverinfo='name', **kwargs) self.current_axis.append(points)
def interactive_marker_target(self, q, **kwargs) : """Marker field display""" if type(q) is not list : q = [q] points = [] separator = np.array([None]* self.dimension) for curve in q : points.append( curve.to_plot() ) points.append( separator ) points = np.vstack(points) points = go.Scatter(x = np.array(points[:,0]), y = np.array(points[:,1]), mode = 'lines', hoverinfo='name', **kwargs) self.current_axis.append(points)
def interactive_show_transport(self, transports, **kwargs) : """Display of a wasserstein transport plan.""" raise(NotImplementedError) points = [] separator = np.array([None]* self.dimension) for trans in transports : (gamma, q, xt) = trans Q = q.to_measure() Xt = xt.to_measure() xtpoints = xt.to_array() for (a, mui, gi) in zip(Q.points, Q.weights, gamma) : # gi = sum(Q.weights) * gi / mui gi = gi / mui for (seg, gij) in zip(xt.connectivity, gi) : mass_per_line = 0.25 if gij >= mass_per_line : #points += [a, b] #points.append( separator ) nlines = floor(gij / mass_per_line) ts = linspace(.35, .65, nlines) for t in ts : b = (1-t) * xtpoints[seg[0]] + t * xtpoints[seg[1]] points += [a, b] points.append( separator ) if points != [] : points = vstack(points) points = go.Scatter(x = array(points[:,0]), y = array(points[:,1]), mode = 'lines', hoverinfo='name', **kwargs) else : points = go.Scatter(x = array([0]), y = array([0]), mode = 'lines', hoverinfo='name', **kwargs) self.current_axis.append(points)
def marker_2D(self, q, **kwargs) : # (r,theta) -> (y,x) Q = self.periodize(q) points = go.Scatter(x = array([Q[:,1]]), y = array([Q[:,0]]), mode = 'markers', hoverinfo='name', **kwargs) self.current_axis.append(points)
def show_transport(self, transports, **kwargs) : """Display of a wasserstein transport plan.""" points = [] separator = array([None]* self.dimension) for trans in transports : (gamma, q, xt) = trans Q = q.to_measure() Xt = xt.to_measure() xtpoints = xt.to_array() for (a, mui, gi) in zip(Q.points, Q.weights, gamma) : # gi = sum(Q.weights) * gi / mui gi = gi / mui for (seg, gij) in zip(xt.connectivity, gi) : mass_per_line = 0.25 if gij >= mass_per_line : #points += [a, b] #points.append( separator ) nlines = floor(gij / mass_per_line) ts = linspace(.35, .65, nlines) for t in ts : b = (1-t) * xtpoints[seg[0]] + t * xtpoints[seg[1]] points += [a, b] points.append( separator ) if points != [] : points = vstack(points) points = go.Scatter(x = array(points[:,0]), y = array(points[:,1]), mode = 'lines', hoverinfo='name', **kwargs) else : points = go.Scatter(x = array([0]), y = array([0]), mode = 'lines', hoverinfo='name', **kwargs) self.current_axis.append(points)
def interactive_plot_traj(self, qts, **kwargs) : """Trajectory display. qt can be an array of coordinates, or a list of such arrays.""" if type(qts[0]) is not list : qts = [qts] points = [] separator = np.array([None]* self.dimension).reshape((1,self.dimension)) for qt in qts : for curve in qt : points.append( self.to_plot(curve) ) points.append( separator ) points = np.vstack(points) points = go.Scatter(x = np.array(points[:,0]), y = np.array(points[:,1]), mode = 'lines', hoverinfo='name', **kwargs) self.current_axis.append(points)
def plot_traj(self, qt, **kwargs) : "Trajectory display. qt can be an array of coordinates, or a list of such arrays." if type(qt) is not list : qt = [qt] points = array([]).reshape((0,self.dimension)) # we should pre-allocate... separator = array([None]* self.dimension).reshape((1,self.dimension)) for traj in qt : traj = atleast_2d(traj) ntimes = traj.shape[0] for landmark in range(self.npoints) : traj_landmark = traj[:, landmark*(self.dimension) : landmark*(self.dimension) + self.dimension] points = vstack((points, traj_landmark, separator)) points = go.Scatter(x = array(points[:,0]), y = array(points[:,1]), mode = 'markers+lines', hoverinfo='name', **kwargs) self.current_axis.append(points)
def marker(self, q, **kwargs) : """Marker field display""" q = atleast_2d(q) list_points = [] separator = array([None]* self.dimension) for l in range(q.shape[0]) : list_points.append(q[l].reshape((self.npoints, self.dimension))) list_points.append( separator ) points = vstack(list_points) points = go.Scatter(x = array(points[:,0]), y = array(points[:,1]), mode = 'markers', hoverinfo='name', **kwargs) self.current_axis.append(points)
def make_line_obj(table, x, yname): '''Makes life easier- ingests x & string of y and make the pyplot''' obj = go.Scatter( x=dates, y=table[yname], mode = 'lines', name = str(yname) ) return obj
def dist_plot(rating_df): x = np.linspace(0, 50, 500) data_dict = {} for row in rating_df.iterrows(): label_name = (row[1]['first_name'] + ' ' + row[1]['last_name'][0] + '.') data_dict[label_name] = (x, mlab.normpdf(x, row[1]['rating'], row[1]['sigma'])) final_df = pd.DataFrame() for k, v in data_dict.iteritems(): final_df[k] = v[1] final_df['index'] = x final_df.set_index('index', inplace=True) trace_dict = dict() for n, col in enumerate(final_df.columns): trace_dict[n] = go.Scatter( x=final_df.index, y=final_df[col], name=col ) data = trace_dict.values() # Edit the layout layout = dict(title='Individual Gaussian Skill Distribution', xaxis=dict(title='Mu'), yaxis=dict(title='Value'), height=750 ) return offl.plot(dict(data=data, layout=layout), output_type='div')