我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用networkx.draw()。
def draw(self, label_nodes=False): """Draw the graph using matplotlib in a color-coordinated manner.""" try: import matplotlib.pyplot as plt print 'Node colors: red=core, blue=major-building, green=distribution, yellow=minor-building, cyan=server,' \ ' magenta=host, black=floor-switch, white=rack-switch, white=cloud, green=gateway' # TODO: ignore building internals? colormap = {'c': 'r', 'b': 'b', 'd': 'g', 'm': 'y', 's': 'c', 'h': 'm', 'f': 'k', 'r': 'w', 'x': 'w', 'g': 'g'} node_colors = [colormap[node[0]] for node in self.topo.nodes()] # shell layout places nodes as a series of concentric circles positions = nx.shell_layout(self.topo, [self.core_nodes, # sort the building routers by degree in attempt to get ones connected to each other next to each other sorted(self.major_building_routers, key=lambda n: nx.degree(self.topo, n)) + self.distribution_routers + self.server_nodes, self.hosts + self.minor_building_routers]) # then do a spring layout, keeping the inner nodes fixed in positions positions = nx.spring_layout(self.topo, pos=positions, fixed=self.core_nodes + self.server_nodes + self.major_building_routers + self.distribution_routers) nx.draw(self.topo, node_color=node_colors, pos=positions, with_labels=label_nodes) plt.show() except ImportError: print "ERROR: couldn't draw graph as matplotlib.pyplot couldn't be imported!"
def nx_plot_tree(server, node_size=200, **options): """Visualize the tree using the networkx package. This plots to the current matplotlib figure. Args: server: A DataServer instance. options: Options passed to networkx.draw(). """ import networkx as nx edges = server.estimate_tree() perplexity = server.latent_perplexity() feature_names = server.feature_names V = 1 + len(edges) G = nx.Graph() G.add_nodes_from(range(V)) G.add_edges_from(edges) H = nx.relabel_nodes(G, dict(enumerate(feature_names))) node_size = node_size * perplexity / perplexity.max() options.setdefault('alpha', 0.2) options.setdefault('font_size', 8) nx.draw(H, with_labels=True, node_size=node_size, **options)
def draw(passage): G = nx.DiGraph() terminals = sorted(passage.layer(layer0.LAYER_ID).all, key=operator.attrgetter("position")) G.add_nodes_from([(n.ID, {"label": n.text, "node_color": "white"}) for n in terminals]) G.add_nodes_from([(n.ID, {"label": "IMPLICIT" if n.attrib.get("implicit") else "", "node_color": "gray" if isinstance(n, Linkage) else ( "white" if n.attrib.get("implicit") else "black")}) for n in passage.layer(layer1.LAYER_ID).all]) G.add_edges_from([(n.ID, e.child.ID, {"label": e.tag, "style": "dashed" if e.attrib.get("remote") else "solid"}) for layer in passage.layers for n in layer.all for e in n]) pos = topological_layout(passage) nx.draw(G, pos, arrows=False, font_size=10, node_color=[d["node_color"] for _, d in G.nodes(data=True)], labels={n: d["label"] for n, d in G.nodes(data=True) if d["label"]}, style=[d["style"] for _, _, d in G.edges(data=True)]) nx.draw_networkx_edge_labels(G, pos, font_size=8, edge_labels={(u, v): d["label"] for u, v, d in G.edges(data=True)})
def draw_graph(gv, ge, name): Gr = nx.Graph() for i in range(N): Gr.add_node(i, pos=gv[i]) for i in range(N): for j in range(N): if ge[i][j]: Gr.add_edge(i,j) labels = dict() for i in range(N): labels[i] = str(i) pos=nx.get_node_attributes(Gr,'pos') nx.draw(Gr, pos=pos, node_size=400, with_labels=False) nx.draw_networkx_labels(Gr, pos, labels) plt.savefig(name)
def DrawDFSPath(G, dfs_stk): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)]) nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges for i in dfs_stk: #if there is more than one node in the dfs-forest, then print the corresponding edges if len(i) > 1: for j in i[ :(len(i)-1)]: if i[i.index(j)+1] in G[j]: nx.draw_networkx_edges(G, pos, edgelist = [(j,i[i.index(j)+1])], width = 2.5, alpha = 0.6, edge_color = 'r') else: #if in case the path was reversed because all the possible neighbours were visited, we need to find the adj node to it. for k in i[1::-1]: if k in G[j]: nx.draw_networkx_edges(G, pos, edgelist = [(j,k)], width = 2.5, alpha = 0.6, edge_color = 'r') break #main function
def _render(self, mode = "human", close = False): if close: return import matplotlib.pyplot as plt if self.tick == 0: plt.ion() G = self.G attrs = nx.get_node_attributes(G, "ndd") values = ["red" if attrs[v] else "blue" for v in G.nodes()] plt.clf() nx.draw(G, pos = nx.circular_layout(G), node_color = values) plt.pause(0.01) return []
def plot_workflow_graph_image(self): """ Show the image from workflow_graph """ # Change layout according to necessity pos = nx.spring_layout(self.graph) nx.draw(self.graph, pos, node_color='#004a7b', node_size=2000, edge_color='#555555', width=1.5, edge_cmap=None, with_labels=True, style='dashed', label_pos=50.3, alpha=1, arrows=True, node_shape='s', font_size=8, font_color='#FFFFFF') # Must import pyplot here! import matplotlib.pyplot as plt plt.show() # If necessary save the image # plt.savefig(filename, dpi=300, orientation='landscape', format=None, # bbox_inches=None, pad_inches=0.1)
def vis_graph(graph, name='net2net', show=False): path = osp.dirname(name) name = osp.basename(name) if path == '': path = name mkdir_p(osp.join(root_dir, "output", path), delete=False) restore_path = os.getcwd() os.chdir(osp.join(root_dir, "output", path)) with open(name + "_graph.json", "w") as f: f.write(graph.to_json()) try: plt.close('all') nx.draw(graph, with_labels=True) if show: plt.show() plt.savefig('graph.png') # plt.close('all') except Exception as inst: logger.warning(inst) os.chdir(restore_path)
def plot(self): # print(list(self.root.edge_list())) labels = {} for i, j in self.root.edge_list(): labels[i] = i labels[j] = j G = nx.Graph(self.root.edge_list()) pos = graphviz_layout(G, prog='dot') nx.draw(G, pos) nx.draw_networkx_labels(G, pos, labels) plt.show() # class BST_count(BST): # def __init__(self, url=None, file=None,tree=None): # if tree: # pass # else: # super(BST).__init__(url,file)
def draw_wsn(motes=None, algo='quadrants', **kwargs): """ This function allows to draw the list of motes generated with one of the WSN generation functions hereafter. :param motes: a list of motes as output by one of the WSN generation functions hereafter """ assert algo in __all__ import networkx as nx from matplotlib import pyplot as plt motes = motes or eval(algo)(**kwargs) wsn = nx.Graph() for mote in motes: wsn.add_node(mote['id']) pos = {m['id']: (m['x'], m['y']) for m in motes} col = ['green'] + (len(motes) - 2) * ['blue'] + ['red'] nx.draw(wsn, pos, node_color=col) plt.show()
def draw_loop(): """ Draw the graph in a loop """ global G plt.ion() # mng = plt.get_current_fig_manager() # mng.resize(*mng.window.maxsize()) plt.draw() for line in fileinput.input(): if output(line): plt.clf() nx.draw(G) plt.draw()
def draw_net_using_node_coords(net): """ Plot a networkx.Graph by using the lat and lon attributes of nodes. Parameters ---------- net : networkx.Graph Returns ------- fig : matplotlib.figure the figure object where the network is plotted """ import matplotlib.pyplot as plt fig = plt.figure() node_coords = {} for node, data in net.nodes(data=True): node_coords[node] = (data['lon'], data['lat']) ax = fig.add_subplot(111) networkx.draw(net, pos=node_coords, ax=ax, node_size=50) return fig
def plot_graph(self, file_name: str='graph.png', label_nodes: bool=True, label_edges: bool=True): import matplotlib.pyplot as plt # pos = nx.spring_layout(self.graph) pos = nx.shell_layout(self.graph, dim=1024, scale=0.5) # pos = nx.random_layout(self.graph, dim=1024, scale=0.5) if label_edges: edge_labels = { (edge[0], edge[1]): edge[2]['object'] for edge in self.graph.edges(data=True) } nx.draw_networkx_edge_labels(self.graph, pos, edge_labels, font_size=5) if label_nodes: labels = {node[0]: node[1] for node in self.graph.nodes(data=True)} nx.draw_networkx_labels(self.graph, pos, labels, font_size=5, alpha=0.8) # nx.draw(self.graph, with_labels=True, arrows=True, node_size=80) nx.draw_spectral(self.graph, with_labels=True, arrows=True, node_size=80) plt.savefig(file_name, dpi=1024)
def plot_cumulative_gains(lift: pd.DataFrame): fig, ax = plt.subplots() fig.canvas.draw() handles = [] handles.append(ax.plot(lift['PercentCorrect'], 'r-', label='Percent Correct Predictions')) handles.append(ax.plot(lift['PercentCorrectBestCase'], 'g-', label='Best Case (for current model)')) handles.append(ax.plot(lift['PercentAvgCase'], 'b-', label='Average Case (for current model)')) ax.set_xlabel('Total Population (%)') ax.set_ylabel('Number of Respondents (%)') ax.set_xlim([0, 9]) ax.set_ylim([10, 100]) try: labels = [int((label+1)*10) for label in [float(item.get_text()) for item in ax.get_xticklabels() if len(item.get_text()) > 0]] except BaseException as e: print([item.get_text() for item in ax.get_xticklabels()]) ax.set_xticklabels(labels) fig.legend(handles, labels=[h[0].get_label() for h in handles]) fig.show()
def draw_tier2(): print 'loading tier2 data' loadEntity(tier2filename) print 'entity size: ', len(entityList) G = nx.Graph() G.add_node(u'???') for entity in entityList: name = entity.name[0].decode('utf8') print name G.add_node(name) G.add_edge(u'???',name) for child in entity.child: cn = child.decode('utf8') G.add_node(cn) G.add_edge(name, cn) pos=nx.spring_layout(G) # positions for all nodes nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5) # labels nx.draw_networkx_labels(G,pos,font_size=15,font_family='sans-serif') plt.axis('off') plt.show() # draw tier 3 test
def draw_grid(ts, edgelabel='control', prop_colors=None, current_node=None): assert edgelabel is None or nx.is_weighted(ts.g, weight=edgelabel) pos = nx.get_node_attributes(ts.g, 'location') if current_node == 'init': current_node = next(ts.init.iterkeys()) colors = dict([(v, 'w') for v in ts.g]) if current_node: colors[current_node] = 'b' for v, d in ts.g.nodes_iter(data=True): if d['prop']: colors[v] = prop_colors[tuple(d['prop'])] colors = colors.values() labels = nx.get_node_attributes(ts.g, 'label') nx.draw(ts.g, pos=pos, node_color=colors) nx.draw_networkx_labels(ts.g, pos=pos, labels=labels) edge_labels = nx.get_edge_attributes(ts.g, edgelabel) nx.draw_networkx_edge_labels(ts.g, pos=pos, edge_labels=edge_labels)
def draw(self): """Draw the topology""" try: import matplotlib.pyplot as plt except ImportError: log.warning("matplotlib could not be found") return node_color = range(len(self.graph.nodes())) pos = nx.spring_layout(self.graph,iterations=200) nx.draw(self.graph,pos,node_color=node_color, node_size=[100*(nx.degree(self.graph,x)**1.25) for x in self.graph.nodes()], edge_color=['blue' for x,y,z in self.graph.edges(data=True)], edge_cmap=plt.cm.Blues, with_labels=True, cmap=plt.cm.Blues) plt.show()
def test_subgraph_within_box(self): bounding_box = box(121.428387, 31.027371, 121.430863, 31.030227) a = time.time() subgraph = self.sg.subgraph_within_box(bounding_box) print(time.time() - a) if self.show_plots: plt.figure() nx.draw(subgraph, pos=self.sg.node_xy, node_size=50) plt.show()
def graphNetworkx(self, buds_visible = False, filter_assym_edges = False, labels_visible = True, iterations = 1000): self.buds_visible = buds_visible self.filter_assym_edges = filter_assym_edges G = self.makeGraphData() if hasattr(self, 'nodeColorInfo'): nodeColors = self.useColorData(G, 'networkx') #print G.node if labels_visible: nx.draw_networkx(G, pos=nx.spring_layout(G, iterations = iterations), node_color = nodeColors, linewidths = 1) else: nx.draw(G, pos=nx.spring_layout(G, iterations = iterations), node_color = nodeColors, linewidths = 1) plt.show()
def DrawGraph(B): l, r = nx.bipartite.sets(B) pos = {} # Update position for node from each group pos.update((node, (1, index)) for index, node in enumerate(l)) pos.update((node, (2, index)) for index, node in enumerate(r)) nx.draw(B, pos, with_labels = True) #with_labels=true is to show the node number in the output graph edge_labels = dict([((u, v), d['length']) for u, v, d in B.edges(data = True)]) nx.draw_networkx_edge_labels(B, pos, edge_labels = edge_labels, label_pos = 0.2, font_size = 11) #prints weight on all the edges return pos #main function
def CreateResultGraph(sorted_list): D = nx.DiGraph() for i in range(len(sorted_list)-1): D.add_edge(sorted_list[i], sorted_list[i+1]) pos = nx.spring_layout(D) val_map = {} val_map[sorted_list[0]] = 'green' val_map[sorted_list[len(sorted_list)-1]] = 'red' values = [val_map.get(node, 'blue') for node in D.nodes()] nx.draw(D, pos, with_labels = True, node_color =values) #takes input from the file and creates a directed graph
def DrawGraph(G): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True, node_color ='blue') #with_labels=true is to show the node number in the output graph return pos #main function
def DrawGraph(G,color): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True, edge_color = color) #with_labels=true is to show the node number in the output graph edge_labels = nx.get_edge_attributes(G,'length') nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges return pos #main function
def DrawGraph(G,col_val): pos = nx.spring_layout(G) values = [col_val.get(node, 'blue') for node in G.nodes()] nx.draw(G, pos, with_labels = True, node_color = values, edge_color = 'black' ,width = 1, alpha = 0.7) #with_labels=true is to show the node number in the output graph #main function
def DrawGraph(G): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)]) nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges return pos #main function
def DrawPath(G, source, dest): pos = nx.spring_layout(G) val_map = {} val_map[source] = 'green' val_map[dest] = 'red' values = [val_map.get(node, 'blue') for node in G.nodes()] nx.draw(G, pos, with_labels = True, node_color = values, edge_color = 'b' ,width = 1, alpha = 0.7) #with_labels=true is to show the node number in the output graph edge_labels = dict([((u, v,), d['length']) for u, v, d in G.edges(data = True)]) nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.5, font_size = 11) #prints weight on all the edges return pos #main function
def DrawGraph(G, centers): pos = nx.spring_layout(G) color_map = ['blue'] * len(G.nodes()) #all the center nodes are marked with 'red' for c in centers: color_map[c] = 'red' nx.draw(G, pos, node_color = color_map, with_labels = True) #with_labels=true is to show the node number in the output graph edge_labels = nx.get_edge_attributes(G, 'length') nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges #main function
def DrawGraph(G): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph edge_labels = nx.get_edge_attributes(G,'length') nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges return pos #main function
def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.2) #with_labels=true is to show the node number in the output graph nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'blue') nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'blue', alpha = 0.5) return pos
def DrawGraph(G, egocentric_network_edge_list, egocentric_network_node_list, vert): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.8) #with_labels=true is to show the node number in the output graph nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red') nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5) nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8) return pos
def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list, vert): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.8) #with_labels=true is to show the node number in the output graph nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red') nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5) nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8) return pos
def DrawGraph(G): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph edge_labels = dict([((u, v), d['length']) for u, v, d in G.edges(data = True)]) nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges return pos #main function
def DrawGraph(G): pos = nx.spring_layout(G) nx.draw(G, pos, with_labels = True) # with_labels=true is to show the node number in the output graph edge_labels = nx.get_edge_attributes(G, 'length') nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) # prints weight on all the edges return pos # main function
def draw_graph(G, labels, colors, show, save_path, close_plot=True): nx.draw(G, pos=graphviz_layout(G, prog='dot'), labels=labels, arrows=True, node_color=colors) if show: plt.show() else: plt.savefig(save_path) if close_plot: plt.close()
def debug_instance(instance_wf): print '*' * 20 print instance_wf.graph.nodes(data=False) print '*' * 21 print instance_wf.graph.edges() print '*' * 22 print instance_wf.graph.is_multigraph() print '*' * 23 print instance_wf.graph.number_of_edges() print '*' * 24 print instance_wf.sorted_tasks print '*' * 25 test = instance_wf.graph.reverse() print test.edges() print '*' * 26 print instance_wf.graph.in_degree() print instance_wf.check_in_degree_edges() print '*' * 27 print instance_wf.graph.out_degree() print instance_wf.check_out_degree_edges() print '*' * 28 x = instance_wf.get_operations()[0] print x['ports'] # print instance_wf.get_ports_from_operation_tasks('') # Show image # pos = nx.spring_layout(instance_wf.graph) # pos = nx.fruchterman_reingold_layout(instance_wf.graph) # nx.draw(instance_wf.graph, pos, node_color='#004a7b', node_size=2000, # edge_color='#555555', width=1.5, edge_cmap=None, # with_labels=True, style='dashed', # label_pos=50.3, alpha=1, arrows=True, node_shape='s', # font_size=8, # font_color='#FFFFFF') # plt.show() # plt.savefig(filename, dpi=300, orientation='landscape', format=None, # bbox_inches=None, pad_inches=0.1)
def view_city(self): pos = nx.circular_layout(self.city) node_labels = {} for u in self.city.nodes(): node_labels[u] = u nx.draw(self.city, pos) nx.draw_networkx_labels(self.city, pos, labels=node_labels) self.btnViewCity.setEnabled(True) plt.show()
def show_topology(self): if self.pre_link_to_port != self.link_to_port and setting.TOSHOW: # It means the link_to_port table has changed. _graph = self.graph.copy() print "\n---------------------Link Port---------------------" print '%6s' % ('switch'), for node in sorted([node for node in _graph.nodes()], key=lambda node: node): print '%6d' % node, print for node1 in sorted([node for node in _graph.nodes()], key=lambda node: node): print '%6d' % node1, for node2 in sorted([node for node in _graph.nodes()], key=lambda node: node): if (node1, node2) in self.link_to_port.keys(): print '%6s' % str(self.link_to_port[(node1, node2)]), else: print '%6s' % '/', print print self.pre_link_to_port = self.link_to_port.copy() if self.pre_access_table != self.access_table and setting.TOSHOW: # It means the access_table has changed. print "\n----------------Access Host-------------------" print '%10s' % 'switch', '%10s' % 'port', '%22s' % 'Host' if not self.access_table.keys(): print " NO found host" else: for sw in sorted(self.access_table.keys()): print '%10d' % sw[0], '%10d ' % sw[1], self.access_table[sw] print self.pre_access_table = self.access_table.copy() # nx.draw(self.graph) # plt.savefig("/home/huangmc/exe/matplotlib/%d.png" % int(time.time()))
def plot(self, output=None): import matplotlib.pyplot as plt #pylint:disable=import-error plt.close() networkx.draw(self.make_graph()) if output: plt.savefig(output) else: plt.show()
def visualize(G, savename, savegml): pos = nx.spring_layout(G) # ??????????????????????????? nx.draw(G, pos, with_labels=True,alpha=0.3,font_size=0.0,node_size=10) # ?????? ???????????????????? plt.savefig(savename+".png") plt.show() if savegml: nx.write_gml(G,savename+".gml")
def make_graph(list_of_edges): G = nx.Graph() for x in list_of_edges: pair = tuple(x.split("-", 1)) G.add_edge(pair[0], pair[1]) print len(G.edges()) pos=nx.fruchterman_reingold_layout(G) nx.draw(G,pos) plt.show() return len(list_of_edges)
def draw_dodag(path): """ This function draws the DODAG (to ./results) from the list of motes (from ./simulation.csc) and the list of edges (from ./data/relationships.log). :param path: path to the experiment (including [with-|without-malicious]) """ pyplot.clf() with_malicious = (basename(normpath(path)) == 'with-malicious') data, results = join(path, 'data'), join(path, 'results') with open(join(data, 'relationships.log')) as f: relationships = f.read() # first, check if the mote relationships were recorded if len(relationships.strip()) == 0: return # retrieve motes and their colors dodag = networkx.DiGraph() motes = get_motes_from_simulation(join(path, 'simulation.csc')) dodag.add_nodes_from(motes.keys()) colors = [] for n, p in motes.items(): x, y = p dodag.node[n]['pos'] = motes[n] = (x, -y) colors.append('green' if n == 0 else ('yellow' if not with_malicious or (with_malicious and 0 < n < len(motes) - 1) else 'red')) # retrieve edges from relationships.log edges = {} for relationship in relationships.split('\n'): try: d = match(RELATIONSHIP_REGEX, relationship.strip()).groupdict() if int(d['flag']) == 0: continue mote, parent = int(d['mote_id']), int(d['parent_id']) edges[mote] = parent except AttributeError: continue # now, fill in the graph with edges dodag.add_edges_from(edges.items()) # finally, draw the graph networkx.draw(dodag, motes, node_color=colors, with_labels=True) pyplot.savefig(join(results, 'dodag.png'), arrow_style=FancyArrowPatch)
def main(): edges = [] # ??????? domain_name = 'taobao.com' domain_pkts = get_data(domain_name) for i in domain_pkts[0]['details']: for v in i['answers']: edges.append((v['domain_name'],v['dm_data'])) plt.figure(1, figsize=(10, 8)) G = nx.Graph() G.add_edges_from(edges) pos = graphviz_layout(G, prog="fdp") #neato fdp C = nx.connected_component_subgraphs(G) # ????????????? for g in C: c = [random.random()] * nx.number_of_nodes(g) nx.draw(g, pos, node_size=90, node_color=c, vmin=0.0, vmax=1.0, with_labels=False ) plt.savefig('./graph/'+domain_name+"_relation.png", dpi=75) plt.show()
def draw(self, filename="network_view.png"): """ Draw this graph to a file, for debugging. """ import matplotlib.pyplot as plt plt.clf() pos = circular_layout(self.graph) draw(self.graph, pos, with_labels=False, arrows=False, hold=False, edge_color=[self.graph[u][v]['color'] for u,v in self.graph.edges()], node_color=['orange' if v in self._all_addresses else 'green' for v in self.graph.nodes()]) plt.savefig(filename)
def plot_csv(target_dir='', columns=0, sep=' ', separate=False, title=None): if type(columns) is not list: columns = [columns] title = title or 'LDA Inference' xlabel = 'Iterations' markers = cycle([ '+', '*', ',', 'o', '.', '1', 'p', ]) if not separate: fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_xlabel(xlabel) ax1.set_title(title) for column in columns: if separate: fig = plt.figure() plt.title(title) plt.xlabel('xlabel') ax1 = plt.gca() filen = os.path.join(os.path.dirname(__file__), "../PyNPB/data/", target_dir) with open(filen) as f: data = f.read() data = filter(None, data.split('\n')) data = [x.strip() for x in data if not x.startswith(('#', '%'))] ll_y = [row.split(sep)[column] for row in data] ylabel, label = tag_from_csv(column) ax1.set_ylabel(ylabel) #ax1.plot(ll_y, c='r',marker='x', label='log likelihood') ax1.plot(ll_y, marker=next(markers), label=label) leg = ax1.legend() plt.draw()
def log_binning(counter_dict,bin_count=35): max_x = np.log10(max(counter_dict.keys())) max_y = np.log10(max(counter_dict.values())) max_base = max([max_x,max_y]) min_x = np.log10(min(drop_zeros(counter_dict.keys()))) bins = np.logspace(min_x,max_base,num=bin_count) # Based off of: http://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy #bin_means_y = (np.histogram(counter_dict.keys(),bins,weights=counter_dict.values())[0] / np.histogram(counter_dict.keys(),bins)[0]) #bin_means_x = (np.histogram(counter_dict.keys(),bins,weights=counter_dict.keys())[0] / np.histogram(counter_dict.keys(),bins)[0]) bin_means_y = np.histogram(counter_dict.keys(),bins,weights=counter_dict.values())[0] bin_means_x = np.histogram(counter_dict.keys(),bins,weights=counter_dict.keys())[0] return bin_means_x,bin_means_y #def plot_degree(y, title=None, noplot=False): # if len(y) > 6000: # return # G = nxG(y) # degree = sorted(nx.degree(G).values(), reverse=True) # if noplot: # return degree # #plt.plot(degree) # x = np.arange(1, y.shape[0] + 1) # fig = plt.figure() # plt.loglog(x, degree) # if title: # plt.title(title) # plt.draw() # #def plot_degree_(y, title=None): # if len(y) > 6000: # return # G = nxG(y) # degree = sorted(nx.degree(G).values(), reverse=True) # x = np.arange(1, y.shape[0] + 1) # plt.loglog(x, degree) # if title: # plt.title(title)
def draw_blocks(comm): #nx.draw(H,G.position, # node_size=[G.population[v] for v in H], # node_color=node_color, # with_labels=False) blocks = comm.get('block_hist') ties = comm.get('block_ties') blocks = 2*blocks / np.linalg.norm(blocks) max_n = max(blocks) G = nx.Graph(nodesep=0.7) u_colors.reset() ind_color = np.arange(0, len(blocks)**2, 2) % len(u_colors.seq) #ind_color = np.diag(np.arange(len(blocks)**2).reshape([len(blocks)]*2)) % len(u_colors.seq) colors = np.array(u_colors.seq)[ind_color] # if sorted sorted_blocks, sorted_ind = zip(*sorted( zip(blocks, range(len(blocks))) , reverse=True)) for l, s in enumerate(sorted_blocks): if s == 0: continue G.add_node(int(l), width=s, height=s, fillcolor=colors[l], style='filled') max_t = max(ties, key=lambda x:x[1])[1] if max_t > max_n: scale = np.exp(2) * float(max_n) / max_t for l, s in ties: i, j = l # if sorted i = sorted_ind.index(int(i)) j = sorted_ind.index(int(j)) G.add_edge(i, j, penwidth = s * scale) return write_dot(G, 'graph.dot')
def draw_graph_circular(y, clusters='blue', ns=30): G = nxG(y) pos = graphviz_layout(G, prog='twopi', args='') plt.figure() nx.draw(G, pos, node_size=ns, alpha=0.8, node_color=clusters, with_labels=False) plt.axis('equal')
def adjshow_4(Y,title=[], pixelspervalue=20): minvalue = np.amin(Y) maxvalue = np.amax(Y) cmap = plt.cm.hot fig = plt.figure() plt.subplot(2,2,1) plt.axis('off') implot = plt.imshow(Y[0], cmap=cmap, clim=(minvalue, maxvalue), interpolation='nearest') plt.title(title[0]) plt.subplot(2,2,2) plt.axis('off') implot = plt.imshow(Y[1], cmap=cmap, clim=(minvalue, maxvalue), interpolation='nearest') plt.title(title[1]) plt.subplot(2,2,3) plt.axis('off') implot = plt.imshow(Y[2], cmap=cmap, clim=(minvalue, maxvalue), interpolation='nearest') plt.title(title[2]) plt.subplot(2,2,4) plt.axis('off') implot = plt.imshow(Y[3], cmap=cmap, clim=(minvalue, maxvalue), interpolation='nearest') plt.title(title[3]) plt.draw() ########################## ### Curve Plot ########################## # @deprecated
def displayMatplot(): # display in matplotlib pos=nx.get_node_attributes(g,'pos') nx.draw(g,pos) plt.show() # plt.savefig("/tmp/path.png")
def run(self): ip_addresses = ['192.168.1.%s' % x for x in range(1, self._number_clients)] ports = [x for x in range(1, 2)] clients = [] progress = 0 for ip_addr in ip_addresses: print_progress(progress, self._number_clients, suffix="Running simulation") for port in ports: progress += 1 client = Client(ip_addr, port, clients[0] if len(clients) > 0 else None, max_chache_size=self._number_connections_per_client) clients.append(client) connection = Connection(client, clients[0]) connection.initiate() bootstrapper_connections = clients[0].get_connections() for conn in bootstrapper_connections: connection = Connection(client, conn.second_client) connection.initiate() graph = networkx.nx.Graph() for client in clients: logging.error(client.get_ident()) logging.error(client.get_connection_idents()) for node in client.get_connections(): graph.add_edge(node.first_client.get_ident(), node.second_client.get_ident()) networkx.draw(graph, with_labels=False) plt.savefig("path_graph.pdf") print("Network is connected: %s" % networkx.is_connected(graph)) print("Average shortest path length: %s" % networkx.average_shortest_path_length(graph)) print("Average bipartite clustering coefficent %s" % networkx.average_clustering(graph)) print("Bipartite clustering coefficent %s" % networkx.clustering(graph)) print("degree_assortativity_coefficient %s" % networkx.degree_assortativity_coefficient(graph))