def circuit_from(bqm): G = bqm.to_networkx_graph() plot = Plot( plot_width=600, plot_height=400, x_range=Range1d(-0.1, 1.1), y_range=Range1d(-0.1, 1.1) ) plot.title.text = "Multiplication as a BQM" plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool()) graph_renderer = from_networkx(G, circuit_layout) circle_size = 25 graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="#F5F7FB") graph_renderer.node_renderer.selection_glyph = Circle(size=circle_size, fill_color="#EEA64E") graph_renderer.node_renderer.hover_glyph = Circle(size=circle_size, fill_color="#FFE86C") edge_size = 2 graph_renderer.edge_renderer.glyph = MultiLine( line_color="#CCCCCC", line_alpha=0.8, line_width=edge_size ) graph_renderer.edge_renderer.selection_glyph = MultiLine( line_color="#EEA64E", line_width=edge_size ) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="#FFE86C", line_width=edge_size) graph_renderer.selection_policy = NodesAndLinkedEdges() graph_renderer.inspection_policy = NodesAndLinkedEdges() plot.renderers.append(graph_renderer) plot.background_fill_color = "#202239" add_labels(plot) show(Row(plot))
def CreateGauge(percentage, scaleInfo): gaugeFig = Plot(x_range=Range1d(start=-1.25, end=1.25), y_range=Range1d(start=-1.25, end=1.25), plot_width=250, plot_height=250) gaugeFig.title.text = "Scale " + str(scaleInfo.Num) + ": " + scaleInfo.Name gaugeFig.title.align = 'center' gaugeFig.toolbar_location = None gaugeFig.border_fill_color = "#101010" gaugeFig.background_fill_color = "#101010" gaugeFig.title.text_color = "white" gaugeFig.outline_line_color = None glyph = AnnularWedge(x=0, y=0, inner_radius=.7, outer_radius=1, start_angle=math.pi / 2 - (2 * math.pi), end_angle=math.pi / 2, fill_color="#444444", name="back") glyph2 = AnnularWedge(x=0, y=0, inner_radius=.7, outer_radius=1, start_angle=math.pi / 2 - (2 * math.pi * percentage), end_angle=math.pi / 2, fill_color=gaugeColors[(scaleInfo.Num - 1) % len(gaugeColors)], name="front") PercentageText = Label(text_align='center', text=str(round((percentage * scaleInfo.MaxCapacity), 1)),text_color = 'white', text_font_size="35px") lowerText = Label(text_align='center', y=-0.25, text=scaleInfo.Units, text_color='white') lowerText2 = Label(text_align='center', y=-0.48, text="Of " + str(scaleInfo.MaxCapacity), text_color='white') gaugeFig.add_glyph(glyph) gaugeFig.add_glyph(glyph2) gaugeFig.add_layout(PercentageText) gaugeFig.add_layout(lowerText) gaugeFig.add_layout(lowerText2) return gaugeFig
def plot_bqm(bqm): """Plot binary quadratic model as a labeled graph.""" g = nx.Graph() g.add_nodes_from(bqm.variables) g.add_edges_from(bqm.quadratic) plot_size = 400 text_size = '16pt' graph = from_networkx(g, nx.spring_layout) graph.node_renderer.glyph = Circle(size=35, fill_color='purple', fill_alpha=0.25) graph.edge_renderer.glyph = MultiLine(line_alpha=0.8, line_width=2) pos = nx.spring_layout(g) data = {'xpos': [], 'ypos': [], 'label': []} for label, loc in pos.items(): data['label'].append(label) data['xpos'].append(loc[0]) data['ypos'].append(loc[1]) labels = LabelSet(x='xpos', y='ypos', text='label', level='glyph', source=ColumnDataSource(data), x_offset=-1, y_offset=-1, text_color="blue", text_font_size='14pt', text_font_style='bold') plot = Plot(plot_width=plot_size, plot_height=plot_size, x_range=Range1d(-1.3, 1.3), y_range=Range1d(-1.3, 1.3)) plot.title.text = "BQM with {} nodes and {} edges".format(len(bqm), len(bqm.quadratic)) tools = [WheelZoomTool(), ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()] plot.add_tools(*tools) plot.toolbar.active_scroll = tools[0] plot.renderers.append(graph) plot.add_layout(labels) plot.background_fill_color = "lightyellow" show(plot)
def test_no_border_or_background_fill(output_file_url, selenium, screenshot): # Have body background-color that should appear through the no-fill plot template = Template(""" <!doctype html> <html lang="en"> <head> {{ bokeh_js }} {{ bokeh_css}} <style> body { background-color: lightblue; } </style> </head> <body> {{ plot_script }} {{ plot_div }} </body> </html> """) plot = Plot(plot_height=HEIGHT, plot_width=WIDTH, x_range=Range1d(0, 10), y_range=Range1d(0, 10), toolbar_location=None) # This is the no-fill that we're testing plot.background_fill_color = None plot.border_fill_color = None plot.add_glyph(Circle(x=3, y=3, size=50, fill_color='#ffffff')) plot.add_glyph(Circle(x=6, y=6, size=50, fill_color='#ffffff')) plot.add_layout( LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="30pt"), 'left') plot.add_layout( LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="30pt"), 'below') html = file_html(plot, INLINE, template=template) # filename has to match test function + '.html' light filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_no_border_or_background_fill.html") with io.open(filepath, "w", encoding="utf-8") as f: f.write(decode_utf8(html)) selenium.get(output_file_url) assert has_no_console_errors(selenium) assert screenshot.is_valid()
def test_no_border_or_background_fill(output_file_url, selenium, screenshot): # Have body background-color that should appear through the no-fill plot template = Template(""" <!doctype html> <html lang="en"> <head> {{ bokeh_js }} {{ bokeh_css}} <style> body { background-color: lightblue; } </style> </head> <body> {{ plot_script }} {{ plot_div }} </body> </html> """) plot = Plot(plot_height=HEIGHT, plot_width=WIDTH, x_range=Range1d(0, 10), y_range=Range1d(0, 10), toolbar_location=None) # This is the no-fill that we're testing plot.background_fill_color = None plot.border_fill_color = None plot.add_glyph(Circle(x=3, y=3, size=50, fill_color='#ffffff')) plot.add_glyph(Circle(x=6, y=6, size=50, fill_color='#ffffff')) plot.add_layout(LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="30pt"), 'left') plot.add_layout(LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="30pt"), 'below') html = file_html(plot, INLINE, template=template) # filename has to match test function + '.html' light filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_no_border_or_background_fill.html") with io.open(filepath, "w", encoding="utf-8") as f: f.write(decode_utf8(html)) selenium.get(output_file_url) assert has_no_console_errors(selenium) screenshot.assert_is_valid()
def draw(S, position=None, with_labels=False): """Plot the given signed social network. Args: S: The network position (dict, optional): The position for the nodes. If no position is provided, a layout will be calculated. If the nodes have 'color' attributes, a Kamanda-Kawai layout will be used to group nodes of the same color together. Otherwise, a circular layout will be used. Returns: A dictionary of positions keyed by node. Examples: >>> import dwave_structural_imbalance_demo as sbdemo >>> gssn = sbdemo.GlobalSignedSocialNetwork() >>> nld_before = gssn.get_node_link_data('Syria', 2013) >>> nld_after = gssn.solve_structural_imbalance('Syria', 2013) # draw Global graph before solving; save node layout for reuse >>> position = sbdemo.draw('syria.png', nld_before) # draw the Global graph; reusing the above layout, and calculating a new grouped layout >>> sbdemo.draw('syria_imbalance.png', nld_after, position) >>> sbdemo.draw('syria_imbalance_grouped', nld_after) """ # we need a consistent ordering of the edges edgelist = S.edges() nodelist = S.nodes() def layout_wrapper(S): pos = position if pos is None: try: # group bipartition if nodes are colored dist = defaultdict(dict) for u, v in product(nodelist, repeat=2): if u == v: # node has no distance from itself dist[u][v] = 0 elif nodelist[u]['color'] == nodelist[v]['color']: # make same color nodes closer together dist[u][v] = 1 else: # make different color nodes further apart dist[u][v] = 2 pos = nx.kamada_kawai_layout(S, dist) except KeyError: # default to circular layout if nodes aren't colored pos = nx.circular_layout(S) return pos # call layout wrapper once with all nodes to store position for calls with partial graph position = layout_wrapper(S) plot = Plot(plot_width=600, plot_height=400, x_range=Range1d(-1.2, 1.2), y_range=Range1d(-1.2, 1.2)) tools = [WheelZoomTool(), ZoomInTool(), ZoomOutTool(), PanTool()] plot.add_tools(*tools) plot.toolbar.active_scroll = tools[0] def get_graph_renderer(S, line_dash): # we need a consistent ordering of the edges edgelist = S.edges() nodelist = S.nodes() # get the colors assigned to each edge based on friendly/hostile sign_edge_color = ['#87DACD' if S[u][v]['sign'] == 1 else '#FC9291' for u, v in edgelist] # get the colors assigned to each node by coloring try: coloring_node_color = ['#4378F8' if nodelist[v]['color'] else '#FFE897' for v in nodelist] except KeyError: coloring_node_color = ['#FFFFFF' for __ in nodelist] graph_renderer = from_networkx(S, layout_wrapper) circle_size = 10 graph_renderer.node_renderer.data_source.add(coloring_node_color, 'color') graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color='color') edge_size = 2 graph_renderer.edge_renderer.data_source.add(sign_edge_color, 'color') try: graph_renderer.edge_renderer.data_source.add([S[u][v]['event_year'] for u, v in edgelist], 'event_year') graph_renderer.edge_renderer.data_source.add( [S[u][v]['event_description'] for u, v in edgelist], 'event_description') plot.add_tools(HoverTool(tooltips=[("Year", "@event_year"), ("Description", "@event_description")], line_policy="interp")) except KeyError: pass graph_renderer.edge_renderer.glyph = MultiLine(line_color='color', line_dash=line_dash) graph_renderer.inspection_policy = EdgesAndLinkedNodes() return graph_renderer try: S_dash = S.edge_subgraph(((u, v) for u, v in edgelist if S[u][v]['frustrated'])) S_solid = S.edge_subgraph(((u, v) for u, v in edgelist if not S[u][v]['frustrated'])) plot.renderers.append(get_graph_renderer(S_dash, 'dashed')) plot.renderers.append(get_graph_renderer(S_solid, 'solid')) except KeyError: plot.renderers.append(get_graph_renderer(S, 'solid')) plot.background_fill_color = "#202239" positions = layout_wrapper(S) if with_labels: data = { 'xpos': [], 'ypos': [], 'label': [] } for label, pos in positions.items(): data['label'].append(label) data['xpos'].append(pos[0]) data['ypos'].append(pos[1]) labels = LabelSet(x='xpos', y='ypos', text='label', level='glyph', source=ColumnDataSource(data), x_offset=-5, y_offset=10, text_color="#F5F7FB", text_font_size='12pt') plot.add_layout(labels) show(Row(plot)) return positions
from bokeh.io import save from bokeh.models import Circle, LinearAxis, Plot, Range1d template =""" {% block preamble %} <style> body { background-color: lightblue; } </style> {% endblock %} """ plot = Plot(plot_width=600, plot_height=600, x_range=Range1d(0, 10), y_range=Range1d(0, 10), toolbar_location=None) # This is the no-fill that we're testing plot.background_fill_color = None plot.border_fill_color = None plot.add_glyph(Circle(x=3, y=3, size=50, fill_color='#ffffff')) plot.add_glyph(Circle(x=6, y=6, size=50, fill_color='#ffffff')) yaxis = LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="40px") plot.add_layout(yaxis, 'left') xaxis = LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="40px") plot.add_layout(xaxis, 'below') save(plot, template=template)
def create_plot(G, layout): ''' Returns a bokeh plot using the given netowrkx graph and layout. Depending on the layout the dimensions of the graphs grid change Parameters: G (networkx graph) : Netoworkx graph that will be plotted layout (networkx layout): The layout of the network graph Return: plot (bokeh Plot): the plot generated using bokehs functions ''' # the grouped layout is a special layout that uses the positions generated # by makegraph.py if layout == "grouped": G, sidel = get_vertices() hsidel = sidel / 2 plot = Plot(plot_width=1200, plot_height=600, x_range=Range1d(-(hsidel + .1), hsidel + .1), y_range=Range1d(-(hsidel + .1), hsidel + .1), align='center') else: plot = Plot(plot_width=1200, plot_height=600, x_range=Range1d(-2.1, 2.1), y_range=Range1d(-2.1, 2.1), align='center') plot.title.text = "TV Shows Connected By Recommendation" plot.background_fill_color = "black" plot.background_fill_alpha = 0.1 if layout == "grouped": pos_dict = {} for node in G.nodes: pos_dict[node] = G.nodes[node]["pos"] graph_renderer = from_networkx(G, pos_dict, scale=hsidel, center=(0, 0)) # The discover layout uses the positions assigned in discover.py elif layout == "discover": pos_dict = {} for node in G.nodes: pos_dict[node] = G.nodes[node]["pos"] graph_renderer = from_networkx(G, pos_dict, scale=2, center=(0, 0)) else: graph_renderer = from_networkx(G, layout, scale=2, center=(0, 0)) # The colors for each node is assigned using a scale and if the number of nodes goes over # 256 the same color is used for the remaining nodes if len(G.nodes) > 256: Inferno = [Spectral4[1]] * len(G.nodes) - 256 Inferno.extend(viridis(len(G.nodes))) else: Inferno = list(viridis(len(G.nodes))) source = graph_renderer.node_renderer.data_source nodes = graph_renderer.node_renderer edges = graph_renderer.edge_renderer source.data['name'] = [x for x in source.data['index']] source.data['colors'] = Inferno nodes.glyph = Circle(size=15, fill_color='colors', fill_alpha=0.9, line_color='colors') nodes.selection_glyph = Circle(size=15, fill_color=Plasma11[10], fill_alpha=0.8) nodes.hover_glyph = Circle(size=15, fill_color=Plasma11[9]) nodes.glyph.properties_with_values() edges.glyph = MultiLine(line_color="black", line_alpha=0.1, line_width=2) edges.selection_glyph = MultiLine(line_color=Plasma11[10], line_width=2) edges.hover_glyph = MultiLine(line_color=Plasma11[9], line_width=2) # This functions allow nodes to be highlighted when hovered over or clicked on graph_renderer.selection_policy = NodesAndLinkedEdges() graph_renderer.inspection_policy = NodesAndLinkedEdges() #graph_renderer.selection_policy = EdgesAndLinkedNodes() # The tooltips to show the data for the plots if layout == "grouped": node_hover_tool = HoverTool(tooltips=[("", "@name"), ("", "@genre")]) else: node_hover_tool = HoverTool(tooltips=[("", "@name")]) plot.add_tools(node_hover_tool, WheelZoomTool(), TapTool(), BoxSelectTool()) plot.renderers.append(graph_renderer) return plot
def draw_graph(self): if len(self.query_topics) <= 10: map_topic_to_color = dict( zip(self.query_topics, [ Category20[20][2 * i] for i in range(len(self.query_topics)) ])) else: map_topic_to_color = dict( zip(self.query_topics, [Category20[20][i] for i in range(len(self.query_topics))])) map_id_to_entity = dict( zip(range(len(self.all_entities)), self.all_entities)) unique_topic = dict([ (entity, max(self.entities_relevant_topics[entity], key=self.entities_relevant_topics[entity].get)) for entity in self.all_entities ]) colors = [] for i in range(len(self.all_entities)): try: colors.append( map_topic_to_color[unique_topic[map_id_to_entity[i]]]) except KeyError: colors.append("#b6b2b2") plot = Plot(plot_width=900, plot_height=900, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1), toolbar_location="below") plot.add_tools( HoverTool(tooltips=[("entity", "@entity"), ("topic", "@topics")]), TapTool(), WheelZoomTool(), LassoSelectTool()) plot.background_fill_color = "#d2d2d2" plot.background_fill_alpha = 0.25 graph = from_networkx(self.graph, nx.spring_layout, scale=2, center=(0, 0)) graph.node_renderer.data_source.column_names.append("size") graph.node_renderer.data_source.data.update({ "size": [ math.log( self.entities_relevant_appearances[map_id_to_entity[i]]) * 5 + 10 for i in range(len(self.all_entities)) ] }) graph.node_renderer.data_source.column_names.append("topics") graph.node_renderer.data_source.data.update({ "topics": [ unique_topic[map_id_to_entity[i]] for i in range(len(self.all_entities)) ] }) graph.node_renderer.data_source.column_names.append("colors") graph.node_renderer.data_source.data.update({"colors": colors}) graph.node_renderer.data_source.column_names.append("entity") graph.node_renderer.data_source.data.update( {"entity": self.all_entities}) graph.node_renderer.glyph = Circle(size="size", fill_color="colors") graph.node_renderer.selection_glyph = Circle(size=8, fill_color=Spectral4[2]) graph.node_renderer.hover_glyph = Circle(size=12, fill_color=Spectral4[1]) graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0., line_width=1.5) graph.edge_renderer.selection_glyph = MultiLine( line_color=Spectral4[2], line_width=1.5) graph.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=2) graph.selection_policy = NodesAndLinkedEdges() graph.inspection_policy = NodesAndLinkedEdges() plot.renderers.append(graph) div = Div(width=1000) layout = row(plot, div) s = graph.node_renderer.data_source s.callback = CustomJS(args=dict(div=div), code=""" var inds = cb_obj.selected['1d'].indices; var args = []; for (i = 0; i < inds.length; i++) { args.push(cb_obj.data['entity'][inds[i]]); } div.text = "<font size='5' color='#9e9e9e'><b>"+args.join("<br />")+"</b></font>" """) show(layout)
def showGraph(self): curdoc().theme = 'dark_minimal' graph_plot = Plot(plot_width=1600, plot_height=900, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) if self._methood: graph_plot.title.text = ( "Graph %s \nTotal Nodes: %i \nTotal Edges: %i \n Node threshold:" "%i \n edge threshold: %i \n Total COMM: %i \n Method: %s" % (self._path[1], self.G.number_of_nodes(), self.G.number_of_edges(), self.nodeThres, self.edgeThres, len(self.partition), self._methood)) else: graph_plot.title.text = "Graph %s. \nTotal Nodes: %i \nTotal Edges: %i \n Node threshold: %i \n edge threshold: %i" % ( self._path[1], self.G.number_of_nodes(), self.G.number_of_edges(), self.nodeThres, self.edgeThres) graph_renderer = from_networkx(self.G, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size='size', fill_color='colors') graph_renderer.node_renderer.hover_glyph = Circle(size=18, fill_color='#E84A5F') graph_renderer.node_renderer.glyph.properties_with_values() graph_renderer.edge_renderer.glyph = MultiLine(line_color="#f2f2f2", line_alpha=0.8, line_width=0.4) graph_renderer.edge_renderer.hover_glyph = MultiLine( line_color='#e09e8f', line_width=3) graph_renderer.node_renderer.data_source.data[ 'hashtag'] = self.data.ht.values graph_renderer.node_renderer.data_source.data[ 'frequency'] = self.data.frq.values graph_renderer.node_renderer.data_source.data[ 'degree'] = self.data.degree.values graph_renderer.node_renderer.data_source.data['ix'] = list( self.data.index) graph_renderer.node_renderer.data_source.data[ 'strength'] = self.data.strength.values graph_renderer.node_renderer.data_source.data['size'] = np.log( (self.data.degree.values + 1) * 3) * 6 if self.community: graph_renderer.node_renderer.data_source.data[ 'colors'] = self.data.color.values graph_renderer.node_renderer.data_source.data[ 'community'] = self.data.community.values node_hover_tool = HoverTool(tooltips=[( "hashtag", "@hashtag"), ("freq", "@frequency"), ( 'degree', '@degree'), ('strength', '@strength'), ('community', '@community'), ('ix', '@ix')]) else: graph_renderer.node_renderer.data_source.data['colors'] = [ 'red' ] * self.G.number_of_nodes() node_hover_tool = HoverTool( tooltips=[("hashtag", "@hashtag"), ( "freq", "@frequency"), ('degree', '@degree'), ('strength', '@strength'), ('ix', '@ix')]) graph_plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(), WheelZoomTool()) graph_plot.toolbar.active_scroll = graph_plot.select_one(WheelZoomTool) graph_renderer.inspection_policy = NodesAndLinkedEdges() graph_renderer.selection_policy = NodesAndLinkedEdges() graph_plot.toolbar.active_inspect = [node_hover_tool] graph_plot.renderers.append(graph_renderer) graph_plot.background_fill_color = '#0d0d0d' graph_plot.background = 'black' graph_plot.border_fill_color = '#1a1a1a' if self.partition: legend = Legend(items=[ LegendItem(label="coverage: %f" % nx.community.coverage(self.G, self.partition), index=0), LegendItem(label="performance: %f" % nx.community.performance(self.G, self.partition), index=1), LegendItem(label="modularity: %f" % nx.community.modularity(self.G, self.partition), index=2) ]) graph_plot.add_layout(legend) output_file(self._path[0] + "Graph_NT" + str(self.nodeThres) + "ET" + str(self.edgeThres) + ".html") show(graph_plot) return