def plot_axis_lines(self, ax, X, color=Tango.colorsHex['mediumBlue'], label=None, marker_kwargs=None, **kwargs): if X.shape[1] == 1: annotations = Annotations() for i, row in enumerate(X): annotations.append( Annotation( text='', x=row[0], y=0, yref='paper', ax=0, ay=20, arrowhead=2, arrowsize=1, arrowwidth=2, arrowcolor=color, showarrow=True, #showlegend=i==0, #label=label, )) return annotations elif X.shape[1] == 2: marker_kwargs.setdefault('symbol', 'diamond') opacity = kwargs.pop('opacity', .8) return Scatter3d(x=X[:, 0], y=X[:, 1], z=np.zeros(X.shape[0]), mode='markers', projection=dict(z=dict(show=True, opacity=opacity)), marker=Marker(color=color, **marker_kwargs or {}), opacity=0, name=label, showlegend=label is not None, **kwargs)
def annotation_heatmap(self, ax, X, annotation, extent=None, label='Gradient', imshow_kwargs=None, **annotation_kwargs): imshow_kwargs.setdefault('label', label) imshow_kwargs.setdefault('showscale', True) imshow = self.imshow(ax, X, extent, **imshow_kwargs) X = X - X.min() X /= X.max() / 2. X -= 1 x = np.linspace(extent[0], extent[1], X.shape[0]) y = np.linspace(extent[2], extent[3], X.shape[1]) annotations = Annotations() for n, row in enumerate(annotation): for m, val in enumerate(row): var = X[n][m] annotations.append( Annotation( text=str(val), x=x[m], y=y[n], xref='x1', yref='y1', font=dict( color='white' if np.abs(var) > 0.8 else 'black', size=10), opacity=.5, showarrow=False, )) return imshow, annotations
def test_validate(): annotations = Annotations() annotations.validate() annotations += [{'text': 'some text'}] annotations.validate() annotations += [{}, {}, {}] annotations.validate()
def make_annotations(pos, text, colorVertex, font_size=14, font_color='rgb(25,25,25)'): L=len(pos[0]) if len(text)!=L: raise ValueError('The lists pos and text must have the same len') annotations = Annotations() for k in range(L): f = getColorText(colorVertex[k]) annotations.append( Annotation( #text=text[k], x=pos[0][k], y=pos[1][k], xref='x1', yref='y1', font=dict(color= f, size=font_size), showarrow=False) ) return annotations
def travelTime(sc, route=False, max_time=False, offset=False): traces = [] tooltip = '<b>Route</b>: {}<br><b>Bus</b>: {}<br>'\ '<b>Arrival</b>: {}<br><b>Departure</b>: {}' for r in range(len(sc.theta)): if r == route: for s in range(len(sc.theta[r])): traces.append( Scatter(x=range(len(sc.theta[r][s])), y=sc.theta[r][s], name="%s (%s-%s)" % (sc.routes.routes[r], sc.routes.routes[r].stops[s], sc.routes.routes[r].stops[s + 1]), line=dict(shape='hv'), showlegend=True)) # if type(offset) is bool: # for route in sc.routes: # traces.append(Scatter( # x=[sc.plan_horizon*2, sc.plan_horizon*2], # y=[route.id, route.id], # mode='lines+markers', # marker=dict( # size=10, # color=[colors[route.id], colors[route.id]] # ), line=dict( # width=5, # color=colors[route.id] # ), showlegend=True, # name='Route %s' % route.name)) max_tt, min_tt = (max(max(max(sc.theta))), min(min(min(sc.theta)))) lo = alter_layout( dict( height=(max_tt - min_tt) * 70, yaxis=dict( zeroline=False, showgrid=False, tickvals=range(0, max_tt + 1), ticktext=map(str, range(0, max_tt + 1)), showticklabels=True, # autorange=False, range=[0, max_tt + 1], title="Travel time(minutes)"), xaxis=dict( showgrid=True, # autotick=False, dtick=10, showticklabels=True, range=[ -1, (sc.plan_horizon + 1) if not max_time else max_time ], autorange=False, title='Time(minutes)'), annotations=Annotations([ Annotation(x=0.5, y=0, showarrow=False, text=sc.name, align='center', xref='paper', yref='paper', font=dict(family='SF Mono', size=11, color='rgba(0,0,0,.2)')) ]))) if len(traces) == 1: traces.append( Scatter(x=[-100], y=[0], line=dict(shape='hv'), showlegend=False)) return Figure(data=traces, layout=alter_layout(dict()))
def comprehensive(soln, sc): traces_all = [] ticks_all = [] n_routes = 0 n_transfers = 0 trs, tks = schedule(soln, sc, offset=0) traces_all += trs ticks_all += tks n_routes = len(tks) trs, tks = connectivity(soln, sc, offset=len(ticks_all) + 1) traces_all += trs ticks_all += tks n_transfers = len(tks) trs, tks = trip(soln, sc, offset=len(ticks_all) + 2) traces_all += trs ticks_all += tks traces_all.append( Scatter(x=[0, sc.plan_horizon, None, 0, sc.plan_horizon], y=[ -n_routes, -n_routes, None, -n_transfers - n_routes - 1, -n_transfers - n_routes - 1 ], mode='lines', line=dict(color='rgba(100,100,100,.3)', width=2, dash='dot'), showlegend=False)) traces_all.append( Scatter(x=[sc.plan_horizon - 14] * 3, y=[0, -n_routes - 1, -n_routes - n_transfers - 2], mode='text', text=['<b>Schedule</b>', '<b>Transfers</b>', '<b>Trips</b>'], textposition='middlright', textfont={ 'size': 13, 'color': '#333333' }, showlegend=False)) for route in sc.routes: traces_all.append( Scatter(x=[sc.plan_horizon * 2, sc.plan_horizon * 2], y=[route.id, route.id], mode='lines+markers', marker=dict(size=10, color=[colors[route.id], colors[route.id]]), line=dict(width=5, color=colors[route.id]), showlegend=True, name='Route %s' % route.name)) lo = alter_layout( dict( hovermode='closest', height=90 + 30 + 30 * (len(ticks_all) + 3), yaxis=dict(zeroline=False, showgrid=False, tickvals=zip(*ticks_all)[0], ticktext=zip(*ticks_all)[1], showticklabels=True, autorange='False', range=[-len(ticks_all) - 2, 1]), xaxis=dict( autorange=False, range=[-1, sc.plan_horizon + 1], showgrid=True, # autotick=False, dtick=10, showticklabels=True), annotations=Annotations([ Annotation(x=0.5, y=-85.0 / 30 / (len(ticks_all) + 3), showarrow=False, text='%s_%s_%s' % (soln.model.timestamp, soln.model.__class__.__name__, sc.name), align='center', xref='paper', yref='paper', font=dict(family='SF Mono', size=11, color='rgba(0,0,0,.2)')) ]))) return Figure(data=traces_all, layout=lo)
def trip(soln, sc, offset=False): """Summary Args: gr (TYPE): Description p (TYPE): Description arr (TYPE): Description dep (TYPE): Description stations (TYPE): Description omega (TYPE): Description alpha (TYPE): Description offset (int, optional): Description Returns: TYPE: Description """ traces = [] for group in sc.groups: sp = group.origin for r, rp, s in zip(group.routes[:-1], group.routes[1:], group.stops): station_r = r.stops.index(s) station_rp = rp.stops.index(s) for k, kp in [(k, kp) for k in range(r.n_buses) for kp in range(rp.n_buses)]: if soln.p[r.id][rp.id][s][k][kp][group.id] == 1: traces.append( Scatter( x=[ soln.d[r.id][r.stops.index(sp)][k], soln.a[r.id][station_r][k] ], y=[-offset - group.id, -offset - group.id], mode='lines+markers', marker=dict(size=10, color=[colors[r.id], colors[r.id]]), line=dict(width=5, color=colors[r.id]), hoverinfo='text', text=[ '<b>Bus</b>: R%s-%s<br><b>Departs</b>: %s' % (r.id, k, soln.d[r.id][r.stops.index(sp)][k]), '<b>Bus</b>: R%s-%s<br><b>Arrives</b>: %s' '<br><b>Transfer time</b>: %s' % (r.id, k, soln.a[r.id][station_r][k], sc.omega[r.id][s][rp.id]) ], showlegend=False)) break sp = s traces.append( Scatter(x=[ soln.d[rp.id][rp.stops.index(sp)][kp], min(soln.d[rp.id][rp.stops.index(sp)][kp] + 5, sc.plan_horizon) ], y=[-offset - group.id, -offset - group.id], mode='lines', line=dict(width=5, color=colors[rp.id], dash="dot"), hoverinfo='text', text=[ '<b>Bus</b>: R%s-%s<br><b>Departs</b>: %s' % (rp.id, kp, soln.d[rp.id][rp.stops.index(sp)][kp]), '' ], showlegend=False)) traces.append( Scatter(x=[soln.d[rp.id][rp.stops.index(sp)][kp]], y=[-offset - group.id], mode='markers', marker=dict(size=10, color=[colors[rp.id], colors[rp.id]]), hoverinfo='text', text=[ '<b>Bus</b>: R%s-%s<br><b>Departs</b>: %s' % (rp.id, kp, soln.d[rp.id][rp.stops.index(sp)][kp]), '' ], showlegend=False)) traces.append( Scatter(x=[g.alpha for g in sc.groups], y=[-y - offset for y in range(len(sc.groups))], mode='markers', marker=dict(size=10, color=[0] * len(sc.groups), colorscale='RdBu', cmin=-1, cmax=1), hoverinfo='text', showlegend=False)) if type(offset) is bool: for route in sc.routes: traces.append( Scatter(x=[sc.plan_horizon * 2, sc.plan_horizon * 2], y=[route.id, route.id], mode='lines+markers', marker=dict(size=10, color=[colors[route.id], colors[route.id]]), line=dict(width=5, color=colors[route.id]), showlegend=True, name='Route %s' % route.name)) lo = alter_layout( dict( hovermode='closest', height=90 + 30 + 30 * (len(sc.groups) + 1), yaxis=dict( zeroline=False, showgrid=False, tickvals=[-x for x in range(len(sc.groups))], # ticktext=[('G%d (' % (g.id, )) + '-'.join([g.origin] + g.stops) + '-)' # for g in sc.groups], ticktext=[ '-'.join([g.origin] + g.stops) + '-S6' for g in sc.groups ], showticklabels=True, autorange=False, range=[-len(sc.groups), 1]), xaxis=dict( autorange=False, range=[-1, sc.plan_horizon + 1], showgrid=True, # autotick=False, dtick=10, showticklabels=True), annotations=Annotations([ Annotation(x=0.5, y=-85.0 / 30 / (len(sc.groups) + 1), showarrow=False, text='%s_%s_%s' % (soln.model.timestamp, soln.model.__class__.__name__, sc.name), align='center', xref='paper', yref='paper', font=dict(family='SF Mono', size=11, color='rgba(0,0,0,.2)')) ]))) return Figure(data=traces, layout=lo) else: return (traces, zip([-y - offset for y in range(len(sc.groups))], [('G%d (' % (g.id, )) + '-'.join([g.origin] + g.stops) + '-)' for g in sc.groups]))
def test_validate_error(): annotations = Annotations() annotations.append({'not-a-key': 'anything'}) annotations.validate()
def test_dict_instantiation_key_error(): print(Annotations([{'not-a-key': 'anything'}]))
def test_dict_instantiation_graph_obj_error_2(): assert Annotations([Annotations()]) == [[]]
def draw3Dnx(graph=None, out_path=None, perc_threshold=None, positions_array=None, positions_dict=None, plot_title='', plot_description='', colorscale='Set3', notebook_mode=True, auto_open=False): """Draws a given graph in 3D""" if graph is None or nx.is_empty(graph): raise ValueError('input graph can not be empty!') # graph = nx.random_geometric_graph(200, 0.05) if notebook_mode: init_notebook_mode() marker_size = 7 marker_edge_width = 2 link_width = 2 colorbar_title = 'Node Connections' hover_description = '# connections: ' position_attr = ['x', 'y', 'z'] if positions_array is not None: for node in graph.nodes(): for ix, attr in enumerate(position_attr): graph.nodes[node][attr] = positions_array[node][ix] elif positions_dict is not None: for node in graph.nodes(): for attr in position_attr: graph.nodes[node][attr] = positions_array[node][attr] for attr in position_attr: if not nx.get_node_attributes(graph, attr): raise ValueError( 'Position attribute {} missing. ' 'Add it to graph or supply with one of the position inputs'. format(attr)) edge_threshold = -np.Inf if perc_threshold is not None: eval_distr = np.array( list(nx.get_edge_attributes(graph, 'weight').values())) try: edge_threshold = np.percentile(eval_distr, perc_threshold) except: print('threshold to prune edges can not be determined.') traceback.print_exc() return edge_trace = Scatter3d( x=[], y=[], z=[], mode='lines', line=Line(width=marker_edge_width, color='#888'), hoverinfo='none', ) def get_position(gnode): """Helper to retun the x, y, z coords of a node""" return gnode['x'], gnode['y'], gnode['z'] for src, dest in graph.edges(): # adding only the strongest edges if perc_threshold is None or graph.get_edge_data( src, dest)['weight'] > edge_threshold: x0, y0, z0 = get_position(graph.nodes[src]) # ['position'] x1, y1, z1 = get_position(graph.nodes[dest]) # ['position'] edge_trace['x'].extend([x0, x1, None]) edge_trace['y'].extend([y0, y1, None]) edge_trace['z'].extend([z0, z1, None]) # empty lists here will be appended with data to be plotted node_trace = Scatter3d(x=[], y=[], z=[], text=[], mode='markers', hoverinfo='text', marker=Marker( symbol='dot', showscale=True, colorscale=colorscale, reversescale=True, color=[], size=marker_size, colorbar=dict(thickness=15, title=colorbar_title, xanchor='left', titleside='right'), )) # setting nodal positions and info for ix, node in enumerate(graph.nodes()): x, y, z = get_position(graph.nodes[node]) node_trace['x'].append(x) node_trace['y'].append(y) node_trace['z'].append(z) node_trace['text'].append(node) node_trace['marker']['color'].append(ix) axis = dict(showbackground=False, showline=False, zeroline=False, showgrid=False, showticklabels=False, title='') scene = Scene(xaxis=XAxis(axis), yaxis=YAxis(axis), zaxis=ZAxis(axis)) annotations = Annotations([ Annotation( showarrow=False, text=plot_description, xref='paper', yref='paper', x=0, y=0.1, # z=0.05, xanchor='left', yanchor='bottom', # zanchor='bottom', font=Font(size=14)) ]) layout = Layout( title=plot_title, titlefont=dict(size=16), # width=1000, # height=1000, showlegend=False, hovermode='closest', scene=scene, margin=Margin(t=100), # margin=dict(b=20,l=5,r=5,t=40), annotations=annotations, ) fig_data = Data([edge_trace, node_trace]) fig = Figure(data=fig_data, layout=layout) if out_path is None and auto_open is False: auto_open = True if notebook_mode: iplot(fig, filename=out_path) else: plot(fig, filename=out_path, auto_open=auto_open) return fig
def test_weird_instantiation(): # Python allows this, but nonsensical for us. assert Annotations({}) == list()
def test_dict_instantiation_key_error_2(): assert Annotations([{"font": "not-a-dict"}]) == [{"font": "not-a-dict"}]
def test_dict_instantiation_graph_obj_error_2(): Annotations([Annotations()])
def test_dict_instantiation_graph_obj_error_0(): Annotations([Data()])
def test_dict_instantiation_key_error(): print(Annotations([{'font': 'not-a-dict'}]))
def schedule(soln, sc, offset=False): """Summary Args: arr (TYPE): Description dep (TYPE): Description rs (TYPE): Description offset (int, optional): Description Returns: TYPE: Description """ arr = [soln.a[0]] dep = [soln.d[0]] traces = [] x_arr = [] y_arr = [] text_arr = [] x_dep = [] y_dep = [] text_dep = [] tooltip = '<b>Route</b>: {}<br><b>Bus</b>: {}<br>'\ '<b>Arrival</b>: {}<br><b>Departure</b>: {}' for r, (arr_r, dep_r) in enumerate(zip(arr, dep)): x_arr += arr_r y_arr += [r] * len(arr_r) text_arr += [ tooltip.format(sc.routes[r].name, k, arr, dep) for k, (arr, dep) in enumerate(zip(arr_r, dep_r)) ] x_dep += dep_r y_dep += [r] * len(dep_r) text_dep += [ tooltip.format(sc.routes[r].name, k, arr, dep) for k, (arr, dep) in enumerate(zip(arr_r, dep_r)) ] traces.append( Scatter(x=x_arr, y=[-y - offset for y in y_arr], mode='markers', marker=dict(size=20, color=[0] * len(x_arr), colorscale='RdBu'), hoverinfo='text', text=text_arr, opacity=.3, showlegend=False)) traces.append( Scatter(x=x_dep, y=[-y - offset for y in y_dep], mode='markers', marker=dict(symbol='triangle-right', size=10, color=[colors[r] for r in y_dep]), hoverinfo='text', text=text_dep, showlegend=False)) if type(offset) is bool: for route in sc.routes: traces.append( Scatter(x=[sc.plan_horizon * 2, sc.plan_horizon * 2], y=[route.id, route.id], mode='lines+markers', marker=dict(size=10, color=[colors[route.id], colors[route.id]]), line=dict(width=5, color=colors[route.id]), showlegend=True, name='Route %s' % route.name)) lo = alter_layout( dict( hovermode='closest', height=30 * (len(sc.routes) + 1) + 30 + 90, yaxis=dict(zeroline=False, showgrid=False, tickvals=[-x for x in range(len(sc.routes))], ticktext=[r.name for r in sc.routes], showticklabels=True, autorange=False, range=[-len(sc.routes), 1]), xaxis=dict( showgrid=True, # autotick=False, dtick=10, showticklabels=True, range=[-1, sc.plan_horizon + 1], autorange=False), annotations=Annotations([ Annotation(x=0.5, y=-85.0 / 30 / (len(sc.routes) + 1), showarrow=False, text='%s_%s_%s' % (soln.model.timestamp, soln.model.__class__.__name__, sc.name), align='center', xref='paper', yref='paper', font=dict(family='SF Mono', size=11, color='rgba(0,0,0,.2)')) ]))) return Figure(data=traces, layout=lo) else: return (traces, zip([-y - offset for y in range(len(sc.routes))], [r.name for r in sc.routes]))
def test_dict_instantiation_key_error(): assert Annotations([{'not-a-key': 'anything'}]) == [{'not-a-key': 'anything'}]
def create_plotly_legends_and_layout(data, title=None, width=None, height=None, x_name=None, y_name=None, x_values=None, y_values=None, x_values_format=None, y_values_format=None, x_categoryarray=None, y_categoryarray=None, x_type=None, y_type=None, x_format=None, y_format=None, x_dtick=None, y_dtick=None,boxmode=None, barmode=None, bargap=None, bargroupgap=None, hovermode=None, annotations=None, shapes=None): ''' This function creates Plotly legends and layout. Parameters - data: Plotly data - title: Title of the graph (by default, None) - width: Width of the figure (by default, None) - height: Height of the figure (by default, None) - x_name: Name of x axis (by default, None) - y_name: Name of y axis (by default, None) - x_values: Array containing x values to display (by default, None / if None, Plotly creates axis automatically) - y_values: Array containing y values to display (by default, None / if None, Plotly creates axis automatically) - x_values_format: Function to use to format x_values (by default, None / if None, x_values is used for x labels) - y_values_format: Function to use to format x_values (by default, None / if None, y_values is used for y labels) - x_categoryarray: Array containing categories in order they must appear on x axis (by default, None) - y_categoryarray: Array containing categories in order they must appear on y axis (by default, None) - x_type: String representing type of x axis (by default, None / type must be supported by Plotly) - y_type: String representing type of y axis (by default, None / type must be supported by Plotly) - x_format: String representing format of x axis (by default, None / format must be supported by Plotly) - y_format: String representing format of y axis (by default, None / format must be supported by Plotly) - x_dtick: Integer representing the spacing between ticks for x axis (by default, None) - y_dtick: Integer representing the spacing between ticks for y axis (by default, None) - boxmode: String representing the type of boxmode to use (by default, None) - barmode: String representing the type of barmode to use (by default, None) . bargap: Float representing the gap between bars (by default, None) . bargroupgap: Float representing the gap between group bars (by default, None) - hovermode: String representing the type of mode to use on hover (by default, None) - annotations: Array containing all Annotation to add in layout (Annotations and Annotation are part of Plotly library / by default, None) - shapes: Array containing all shapes to add in layout (by default, None) Return - figure: Plotly figure ''' if x_values: x_labels = [(x_values_format(v) if x_format else v) for v in x_values] else: x_labels = None if y_values: y_labels = [(y_values_format(v) if y_format else v) for v in y_values] else: y_labels = None x_axis = go.XAxis(title=x_name, categoryorder=('array' if x_categoryarray else None), categoryarray=x_categoryarray, type=x_type, tickformat=x_format, ticktext=x_labels, tickvals=x_values, dtick=x_dtick, mirror='ticks', ticks='inside', showgrid=True, showline=True, zeroline=True, zerolinewidth=2) y_axis = go.YAxis(title=y_name, categoryorder=('array' if y_categoryarray else None), categoryarray=y_categoryarray, type=y_type, tickformat=y_format, ticktext=y_labels, tickvals=y_values, dtick=y_dtick, mirror='ticks', ticks='inside', showgrid=True, showline=True, zeroline=True, zerolinewidth=2) layout = go.Layout(title=title, width=width, height=height, xaxis=x_axis, yaxis=y_axis, boxmode=boxmode, barmode=barmode, bargap=bargap, bargroupgap=bargroupgap, hovermode=hovermode, annotations=Annotations(annotations) if annotations else Annotations(), shapes=shapes if shapes else []) figure = go.Figure(data=data, layout=layout) return figure
def test_weird_instantiation(): # Python allows this, but nonsensical for us. print(Annotations({}))
def test_trivial(): assert Annotations() == list()
def draw_plotly(model, met_names, pairs, fluxes): if not pairs: return G = nx.DiGraph() G.add_edges_from(pairs) if fluxes and type(list(fluxes.values())[0]) == tuple: fl = {} for i in fluxes: fl[i] = fluxes[i][1] producing = set(make_pairs.direct_producers(model, met_names, fl)) consuming = set(make_pairs.direct_consumers(model, met_names, fl)) else: producing = set(make_pairs.direct_producers(model, met_names, fluxes)) consuming = set(make_pairs.direct_consumers(model, met_names, fluxes)) val_map = { 'reaction': '#666699', 'metabolite': '#666699', 'producing': '#006600', 'both': '#663300', 'consuming': '#ff0000', 'observed': "#0066cc", 'path': '#ff66ff' } """ val_map = {'reaction': 'b', 'metabolite': 'c', 'producing': 'g', 'both': 'y', 'consuming': 'r', 'observed': 'm', 'path': 'm'} """ node_colors = [] for node in G.nodes(): if node in met_names: color = val_map['observed'] elif node in producing & consuming: color = val_map['both'] elif node in producing: color = val_map['producing'] elif node in consuming: color = val_map['consuming'] elif node in model.reactions: color = val_map['reaction'] else: color = val_map['metabolite'] node_colors.append(color) node_types = [ 'observed metabolites' if node in met_names else 'producing/consuming reactions' if node in producing & consuming else 'producing reactions' if node in producing else 'consuming reactions' if node in consuming else 'reactions' if node in model.reactions else 'metabolites' for node in G.nodes() ] #node_ids = {node:i for i, node in enumerate(G.nodes())} node_labels = {} for node in G.nodes(): if node in model.reactions: f = fluxes[node] if type(f) == tuple: node_labels[node] = node + " :" + "{:.3f}\n{:.3f}".format( round(f[0], 3), round(f[1], 3)) else: node_labels[node] = node + " :" + "{:.3f}".format( round(fluxes[node], 3)) else: node_labels[node] = node node_sizes = [20 if a in model.reactions else 10 for a in G.nodes()] #pos = nx.nx_pydot.graphviz_layout(G, prog="dot") pos = nx.fruchterman_reingold_layout(G) N = G.nodes() E = G.edges() Xv = [pos[k][0] for k in pos] Yv = [pos[k][1] for k in pos] labels = [node_labels[l] for l in node_labels] #full_labels = [model.reactions[a] if a in model.reactions else model.metabolites[a] for a in G.nodes()] full_labels = [] for i, node in enumerate(G.nodes()): if node in model.reactions: f = fluxes[node] if type(f) == tuple: full_labels.append( model.reactions[node] + " :" + "{:.3f}\n{:.3f}".format(round(f[0], 3), round(f[1], 3))) else: full_labels.append(model.reactions[node] + " :" + "{:.3f}".format(round(fluxes[node], 3))) else: full_labels.append(model.metabolites[node]) Xed = [] Yed = [] for edge in E: Xed += [pos[edge[0]][0], pos[edge[1]][0], None] Yed += [pos[edge[0]][1], pos[edge[1]][1], None] edge_trace = Scatter(x=Xed, y=Yed, mode='lines+markers', line=Line(color='rgb(210,210,210)', width=1), hoverinfo='none') traces = [edge_trace] """ node_trace = Scatter(x=Xv[1:3], y=Yv[1:3], mode='markers', name='dot', marker=Marker(symbol='dot', size=node_sizes[1:3], color= node_colors[1:3], line=Line(color='rgb(50,50,50)', width=0.5) ), text=labels[1:3], hoverinfo='text' ) traces.append(node_trace) node_trace = Scatter(x=Xv[3:], y=Yv[3:], mode='markers', name='dot', marker=Marker(symbol='dot', size=node_sizes[3:], color= node_colors[3:], line=Line(color='rgb(50,50,50)', width=0.5) ), text=labels[3:], hoverinfo='text' ) traces.append(node_trace) """ N_len = len(N) for i in range(N_len): traces.append( Scatter(x=[Xv[i]], y=[Yv[i]], mode='markers', name=node_types[i], marker=Marker(symbol='dot', size=[node_sizes[i]], color=[node_colors[i]], line=Line(color='rgb(50,50,50)', width=0.5)), text=[full_labels[i]], hoverinfo='text')) annot = "" #"This networkx.Graph has the Fruchterman-Reingold layout<br>Code:"+"<a href='http://nbviewer.ipython.org/gist/empet/07ea33b2e4e0b84193bd'> [2]</a>" annotations = Annotations([ Annotation( showarrow=False, text=labels[i], xref='x1', yref='y1', x=Xv[i], #+1, y=Yv[i], #+1, xanchor='left', yanchor='bottom', font=Font(size=14)) for i in range(N_len) ] + [ Annotation( showarrow=False, text=labels[0], xref='x1', yref='y1', x=Xv[0], #+1, y=Yv[0], #+1, xanchor='left', yanchor='bottom', font=Font(size=14)) ]) #print(annotations) axis = dict( showline=False, # hide axis line, grid, ticklabels and title zeroline=False, showgrid=False, showticklabels=False, title='') layout = Layout( title='', titlefont=dict(size=16), showlegend=False, #showlegend=True, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), annotations=annotations, xaxis=XAxis(axis), yaxis=YAxis(axis)) data1 = Data(traces) #Data([edge_trace, node_trace]) fig1 = Figure(data=data1, layout=layout) fig1['layout']['annotations'][0]['text'] = annot #py.iplot(fig1, filename='Coautorship-network-nx') plotly.offline.plot(fig1)
def test_dict_instantiation(): Annotations([{'text': 'annotation text'}])
def treeplot(decision_tree): """""" if len(decision_tree.nodes) == 0: return '' g = igraph.Graph() g.add_vertices(len(decision_tree.nodes)) g.add_edges(decision_tree.edges) # Define posições no espaço para a árvore layout = g.layout_reingold_tilford(mode="out", root=[0], rootlevel=None) # Cria os vértices da árvore Xn = [-node[0] for node in layout] Yn = [-node[1] for node in layout] colors = [ '#333' if node['type'] == 'decision' else '#CACACA' for node in decision_tree.nodes ] nodes = Scatter(x=Xn, y=Yn, mode='markers', marker=dict(symbol='square', size=40, color=colors), text=None, hoverinfo='none') # Escreve rótulos nos vértices annotations = Annotations() for node in decision_tree.nodes: color = '#FFF' if node['type'] == 'decision' else '#000' label = node['label'] if node[ 'type'] == 'decision' else node['label'] + '?' a = Annotation(text=label, x=Xn[node['id']], y=Yn[node['id']], xref='x1', yref='y1', font=dict( color=color, size=9, family='"Open Sans", verdana, arial, sans-serif'), showarrow=False) annotations.append(a) # Cria as arestas da árvore Xe = [] Ye = [] for edge in decision_tree.edges: Xe += [Xn[edge[0]], Xn[edge[1]], None] Ye += [Yn[edge[0]], Yn[edge[1]], None] lines = Scatter(x=Xe, y=Ye, mode='lines+markers+text', line=dict(color='#333', width=2), hoverinfo='none') # Escreve rótulos nas arestas for edge in decision_tree.edges: label = decision_tree.nodes[edge[1]]['value'] X = (Xn[edge[0]] + Xn[edge[1]]) / 2 Y = (Yn[edge[0]] * 1.2 + Yn[edge[1]] * 0.8) / 2 a = Annotation(text=label, x=X, y=Y, xref='x1', yref='y1', font=dict( color='#333', size=14, family='"Open Sans", verdana, arial, sans-serif'), showarrow=False) annotations.append(a) # Cria gráfico data = Data([lines, nodes]) axis = dict(showline=False, zeroline=False, showgrid=False, showticklabels=False) layout = dict(title='', annotations=annotations, font=dict(size=12, family='"Open Sans", verdana, arial, sans-serif'), showlegend=False, xaxis=XAxis(axis), yaxis=YAxis(axis), margin=dict(l=0, r=0, b=0, t=0), hovermode='closest', paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)') fig = dict(data=data, layout=layout) return plot(fig, filename='Decision-Tree', output_type='div', include_plotlyjs=False)
def test_dict_instantiation_key_error_2(): assert Annotations([{'font': 'not-a-dict'}]) == [{'font': 'not-a-dict'}]
def Generate_3DModel(idList, labelList, percentage): network = pd.read_csv("network.csv") L = len(network['TF']) #Values=[network['importance'][k] for k in range(L)] #G=ig.Graph(Edges, directed=False) #layt=G.layout('kk', dim=3) G = Create_Graph(idList, labelList, percentage, netthreshold) N = len(list(G.node())) #--> Numero de nodos V = list(G.node()) # lista con todos los nodos #Edges=[(network['TF'][k], network['target'][k]) for k in range(L)] Edges = list(G.edges()) #layt=nx.spectral_layout(G,dim=3) #layt=nx.spring_layout(G, dim=3) #layt=nx.fruchterman_reingold_layout(G,dim=3) #layt=laytdict.values() #g=nx.Graph() #g.add_nodes_from(V) #g.add_edges_from(Edges) layt = nx.fruchterman_reingold_layout(G, dim=3) #layt = nx.circular_layout(G,scale=10,dim=3) #layt=nx.spring_layout(G,dim=3) laytN = list(layt.values()) Xn = [laytN[k][0] for k in range(N)] # x-coordinates of nodes Yn = [laytN[k][1] for k in range(N)] # y-coordinates Zn = [laytN[k][2] for k in range(N)] # z-coordinates Xe = [] Ye = [] Ze = [] for e in Edges: Xe += [layt[e[0]][0], layt[e[1]][0], None] # x-coordinates of edge ends Ye += [layt[e[0]][1], layt[e[1]][1], None] Ze += [layt[e[0]][2], layt[e[1]][2], None] trace1 = Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines', line=Line(color='rgb(125,125,125)', width=1), hoverinfo='none') trace2 = Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers+text', textposition='top', name='genes', marker=Marker(symbol='dot', size=6, color='#6959CD', colorscale='Viridis', line=Line(color='rgb(50,50,50)', width=1)), text=V, hoverinfo='text') #for node, adjacencies in enumerate(G.adjacency()): #trace2['marker']['color'].append(len(adjacencies)) #node_info = 'Number of connections: '+str(len(adjacencies)) #trace2['text'].append(node_info) axis = dict(showbackground=False, showline=False, zeroline=False, showgrid=False, showticklabels=False, title='') fig = Figure(data=Data([trace1, trace2]), layout=Layout( title="Network (3D visualization)", width=1000, height=1000, showlegend=False, scene=Scene( xaxis=XAxis(axis), yaxis=YAxis(axis), zaxis=ZAxis(axis), ), margin=Margin(t=100), hovermode='closest', annotations=Annotations([ Annotation(showarrow=False, text="", xref='paper', yref='paper', x=0, y=0.1, xanchor='left', yanchor='bottom', font=Font(size=14)) ]), )) py.iplot(fig, filename='networkx3D')
def draw_igraph(self, title, colors=None): (Xn, Yn, Zn), (Xe, Ye, Ze) = self.get_3d_position() trace1 = Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines', line=Line(color='rgb(125,125,125)', width=1, dash=True), hoverinfo='none') trace2 = Scatter3d( x=Xn, y=Yn, z=Zn, mode='markers', name='callers', marker=Marker( symbol='dot', size=[100 * x + 5 for x in list(self.betweenness.values())], color=self.colors, colorscale='Rainbow', opacity=0.5), text=self.nodes, hoverinfo='text') axis = dict(showbackground=False, showline=False, zeroline=False, showgrid=False, showticklabels=False, title='') layout = Layout( title=title, width=1000, height=1000, showlegend=False, scene=Scene( xaxis=XAxis(axis), yaxis=YAxis(axis), zaxis=ZAxis(axis), ), margin=Margin(t=100), hovermode='closest', annotations=Annotations([ Annotation(showarrow=False, text="Data source: ???", xref='paper', yref='paper', x=0, y=0.1, xanchor='left', yanchor='bottom', font=Font(size=14)) ]), ) data = Data([trace1, trace2]) fig = Figure(data=data, layout=layout) iplot(fig, filename='Call Network')
showlegend=False, scene=Scene( xaxis=XAxis(axis), yaxis=YAxis(axis), zaxis=ZAxis(axis), ), margin=Margin( t=100 ), hovermode='closest', annotations=Annotations([ Annotation( showarrow=False, text="", xref='paper', yref='paper', x=0, y=0.1, xanchor='left', yanchor='bottom', font=Font( size=14 ) ) ]), ) data=Data([trace1, trace2]) fig=Figure(data=data, layout=layout) py.plot(fig, filename='Crawler')
annotations=Annotations([ Annotation(x=0.000997987927565, y=0.996414507772, text='top-left', xref='paper', yref='paper', showarrow=False, align='left', font=Font(size=12.0, color='#000000'), opacity=1, xanchor='left', yanchor='top'), Annotation(x=0.000997987927565, y=0.00358549222798, text='bottom-left', xref='paper', yref='paper', align='left', showarrow=False, font=Font(size=12.0, color='#000000'), opacity=1, xanchor='left', yanchor='bottom'), Annotation(x=0.996989939638, y=0.996414507772, text='top-right', xref='paper', yref='paper', align='right', showarrow=False, font=Font(size=12.0, color='#000000'), opacity=1, xanchor='right', yanchor='top'), Annotation(x=0.996989939638, y=0.00358549222798, text='bottom-right', xref='paper', yref='paper', align='right', showarrow=False, font=Font(size=12.0, color='#000000'), opacity=1, xanchor='right', yanchor='bottom') ]),
def connectivity(soln, sc, offset=False): """Summary Args: c (TYPE): Description arr (TYPE): Description dep (TYPE): Description rs (TYPE): Description ss (TYPE): Description o (TYPE): Description offset (int, optional): Description Returns: TYPE: Description """ traces = [] t = 0 ticktext = [] x_arr = [] y_arr = [] r_arr = [] text_arr = [] x_dep = [] y_dep = [] r_dep = [] text_dep = [] for r, v1 in soln.c.iteritems(): for rp, v2 in v1.iteritems(): for s, cs in v2.iteritems(): station_r = sc.routes[r].stops.index(s) station_rp = sc.routes[rp].stops.index(s) x_arr += [a for a in soln.a[r][station_r]] y_arr += [t] * len(soln.a[r][station_r]) r_arr += [r] * len(soln.a[r][station_r]) for k in range(sc.routes[r].n_buses): kp = min([ kp if cs[k][kp] == 1 else 999 for kp in range(sc.routes[rp].n_buses) ]) if kp == 999: text_arr.append('<b>Arrival</b>: %s<br>' '<b>Connects</b>: NC' % soln.a[r][station_r][k]) else: text_arr.append( '<b>Arrival</b>: %s<br>' '<b>Connects</b>: %s-%s' % (soln.a[r][station_r][k], sc.routes[rp].name, kp)) x_dep += [d for d in soln.d[rp][station_rp]] y_dep += [t] * sc.routes[rp].n_buses r_dep += [rp] * sc.routes[rp].n_buses text_dep += [ '{}-{}'.format(sc.routes[rp].name, kp) for kp in range(sc.routes[rp].n_buses) ] ticktext.append('%s-%s (%s)' % (sc.routes[r].name, sc.routes[rp].name, s)) t += 1 traces.append( Scatter(x=x_arr, y=[-y - offset for y in y_arr], mode='markers', marker=dict(size=20, color=[colors[r] for r in r_arr]), hoverinfo='text', text=text_arr, showlegend=False)) traces.append( Scatter(x=x_dep, y=[-y - offset for y in y_dep], mode='markers', marker=dict(symbol='triangle-right', size=10, color=[colors[r] for r in r_dep]), hoverinfo='text', text=text_dep, showlegend=False)) if type(offset) is bool: for route in sc.routes: traces.append( Scatter(x=[sc.plan_horizon * 2, sc.plan_horizon * 2], y=[route.id, route.id], mode='lines+markers', marker=dict(size=10, color=[colors[route.id], colors[route.id]]), line=dict(width=5, color=colors[route.id]), showlegend=True, name='Route %s' % route.name)) lo = alter_layout( dict( hovermode='closest', height=90 + 30 + 30 * (t + 1), yaxis=dict(zeroline=False, showgrid=False, tickvals=[-x for x in range(t)], ticktext=ticktext, showticklabels=True, autorange=False, range=[-t, 1]), xaxis=dict( autorange=False, range=[-1, sc.plan_horizon + 1], showgrid=True, # autotick=False, dtick=10, showticklabels=True), annotations=Annotations([ Annotation(x=0.5, y=-85.0 / 30 / (t + 1), showarrow=False, text='%s_%s_%s' % (soln.model.timestamp, soln.model.__class__.__name__, sc.name), align='center', xref='paper', yref='paper', font=dict(family='SF Mono', size=11, color='rgba(0,0,0,.2)')) ]))) return Figure(data=traces, layout=lo) else: return traces, zip([-y - offset for y in range(t)], ticktext)