我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用networkx.spring_layout()。
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 create_image(g, path): path = os.path.relpath(path) if pygraphviz: a = nx.nx_agraph.to_agraph(g) # ['neato'|'dot'|'twopi'|'circo'|'fdp'|'nop'] a.layout(prog='neato', args="-Goverlap=false -Gsplines=true") # splines=true a.draw(path) elif plt: nodes = g.nodes(True) colors = [attrs['color'] for n, attrs in nodes] labels = {n: attrs['label'] for n, attrs in nodes} if graphviz_layout: pos = graphviz_layout(g) else: pos = nx.spring_layout(g) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color=colors, alpha=0.3) nx.draw_networkx_edges(g, pos, style='solid', alpha=0.2) nx.draw_networkx_labels(g, pos, labels, alpha=0.5) # plt.show() plt.imsave(path) # todo: this is not tested! print 'Image saved to', path
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 save(self, path='out.png'): import networkx import matplotlib.pyplot as plt pos = networkx.spring_layout(self.graph, iterations=500) # pos = networkx.spectral_layout(self.graph) # pos = networkx.shell_layout(self.graph) # pos = networkx.fruchterman_reingold_layout(self.graph) nodelist = list(range(self.num_rooms)) networkx.draw_networkx_nodes(self.graph, pos, nodelist=nodelist) edgelist = sorted(self.edges - self.secret_edges) secret = sorted(self.secret_edges) networkx.draw_networkx_edges(self.graph, pos, edgelist=edgelist, edge_color='k') networkx.draw_networkx_edges(self.graph, pos, edgelist=secret, edge_color='r') networkx.draw_networkx_labels(self.graph, pos, self.labels) plt.savefig(path)
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 Drawsubgraph(HG, DrawGraph): #Draw the graph #print HG.nodes() pos=nx.spring_layout(HG) nx.draw_networkx_edges(HG, pos, alpha=0.4) #nx.draw_networkx_labels(HG, pos, font_size=10, font_family='sans-serif') i = 0 colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua' for key in DrawGraph.keys(): nx.draw_networkx_nodes(HG, pos, nodelist=DrawGraph[key], node_size=20,node_color=colorList[i%len(colorList)]) i = i + 1 plt.title("Network Community Analysis") plt.show() ###========================================================================================
def drawcomgraph(HG, DrawGraph): #Draw the graph #print HG.nodes() pos=nx.spring_layout(HG) nx.draw_networkx_edges(HG, pos, alpha=0.4) nx.draw_networkx_labels(HG, pos, font_size=6, font_family='sans-serif') i = 0 colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua' for key in DrawGraph.keys(): nx.draw_networkx_nodes(HG, pos, nodelist=DrawGraph[key], node_size=100,node_color=colorList[i%len(colorList)]) i = i + 1 plt.title("Network Community Analysis") plt.show() #************************************************************************
def graph_visualize(G, args): import networkx as nx import numpy as np # ??????????????????????????? pos = nx.spring_layout(G) # ?????? ???????????????????? plt.figure() nx.draw_networkx(G, pos, with_labels=False, alpha=0.4,font_size=0.0,node_size=10) plt.savefig(args.directory+"/graph/graph.png") nx.write_gml(G, args.directory+"/graph/graph.gml") # ?????? plt.figure() degree_sequence=sorted(nx.degree(G).values(),reverse=True) dmax=max(degree_sequence) dmin =min(degree_sequence) kukan=range(0,dmax+2) hist, kukan=np.histogram(degree_sequence,kukan) plt.plot(hist,"o-") plt.xlabel('degree') plt.ylabel('frequency') plt.grid() plt.savefig(args.directory+'/graph/degree_hist.png')
def draw_graph(edges): G = nx.DiGraph() G.add_edges_from(edges) values = [1.0 for node in G.nodes()] # Specify the edges you want here edge_colours = ['black' for edge in G.edges()] black_edges = [edge for edge in G.edges()] # Need to create a layout when doing # separate calls to draw nodes and edges pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('Reds'), node_color = values, node_size=4800) nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=True) nx.draw_networkx_labels(G,pos,font_size=12,font_family='sans-serif') plt.axis('off') plt.show() # In[183]:
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 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_overlaid_graphs(original, new_graphs, print_text=False): """ Draws the new_graphs as graphs overlaid on the original topology :type new_graphs: list[nx.Graph] """ import matplotlib.pyplot as plt layout = nx.spring_layout(original) nx.draw_networkx(original, pos=layout) # want to overlay edges in different colors and progressively thinner # so that we can see what edges are in a tree line_colors = 'rbgycm' line_width = 2.0 ** (min(len(new_graphs), len(line_colors)) - 1) # use this for visualising on screen # line_width = 3.0 ** (min(len(new_graphs), len(line_colors)) - 1) # use this for generating diagrams for i, g in enumerate(new_graphs): if print_text: log.info(nx.info(g)) log.info("edges:", list(g.edges())) nx.draw_networkx(g, pos=layout, edge_color=line_colors[i % len(line_colors)], width=line_width) # advance to next line width line_width /= 1.7 # use this for visualising on screen # line_width /= 2.0 # use this for generating diagrams plt.show()
def __init__(self): self.ticks_in_week = 10 self.tick = 0 self.current_date = 0 self.real_sizes = None self.nodes = self.get_graph_nodes() self.nodesizes = self.get_node_sizes() self.dates = self.get_dates() self.edges = self.get_edges() self.iters = (len(self.dates)-1)*self.ticks_in_week - 2 self.curr_edges = self.recalc_edges() self.sizes = self.nodesizes[self.dates[self.current_date]] self.size_inc = self.calc_size_inc() self.g = nx.Graph() self.g.add_nodes_from(self.nodes) self.fig = plt.figure(figsize=(16,9),dpi=240) #self.pos = nx.spring_layout(self.g) self.load_positions() self.resize_pos() self.colors = [random.random() for _ in self.nodes] self.glow_iter = 20
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 draw(self, layout='circular', figsize=None): """Draw all graphs that describe the DGM in a common figure Parameters ---------- layout : str possible are 'circular', 'shell', 'spring' figsize : tuple(int) tuple of two integers denoting the mpl figsize Returns ------- fig : figure """ layouts = { 'circular': nx.circular_layout, 'shell': nx.shell_layout, 'spring': nx.spring_layout } figsize = (10, 10) if figsize is None else figsize fig = plt.figure(figsize=figsize) rocls = np.ceil(np.sqrt(len(self.graphs))) for i, graph in enumerate(self.graphs): ax = fig.add_subplot(rocls, rocls, i+1) ax.set_title('Graph ' + str(i+1)) ax.axis('off') ax.set_frame_on(False) g = graph.nxGraph weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()] nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'), width=2, edge_color=weights) return fig
def draw(self, layout='circular', figsize=None): """Draw graph in a matplotlib environment Parameters ---------- layout : str possible are 'circular', 'shell', 'spring' figsize : tuple(int) tuple of two integers denoting the mpl figsize Returns ------- fig : figure """ layouts = { 'circular': nx.circular_layout, 'shell': nx.shell_layout, 'spring': nx.spring_layout } figsize = (10, 10) if figsize is None else figsize fig = plt.figure(figsize=figsize) ax = fig.add_subplot(1, 1, 1) ax.axis('off') ax.set_frame_on(False) g = self.nxGraph weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()] nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'), width=2, edge_color=weights) return fig
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 show_graph_communities(graph, partition, color_map=None, with_labels=False): if color_map is None: color_map = generate_color_map(partition) pos = nx.spring_layout(graph,k=0.1,iterations=50) comm_nodes = utils.partition_to_comm_nodes_map(partition) for comm, nodes in comm_nodes.items(): nx.draw_networkx_nodes(graph, pos, nodelist=nodes, node_size=400, node_color=color_map.get(comm), label=comm, cmap=plt.cm.jet) if with_labels: nx.draw_networkx_labels(graph, pos, font_size=12) nx.draw_networkx_edges(graph, pos, alpha=0.3) plt.legend() plt.axis('off') plt.show()
def show_graph(graph, with_labels=False): pos = nx.spring_layout(graph) nx.draw_networkx_nodes(graph, pos, node_size=200, node_color='red') if with_labels: nx.draw_networkx_labels(graph, pos, font_size=12) nx.draw_networkx_edges(graph, pos, alpha=0.3) plt.axis('off') plt.show()
def draw_partition(graph, partition): # requires matplotlib.pyplot, uncomment above # uses community code and sample from http://perso.crans.org/aynaud/communities/ to draw matplotlib graph in shades of gray g = graph count = 0 size = float(len(set(partition.values()))) pos = nx.spring_layout(g) for com in set(partition.values()): count = count + 1 list_nodes = [nodes for nodes in partition.keys() if partition[nodes] == com] nx.draw_networkx_nodes(g, pos, list_nodes, node_size=20, node_color=str(count / size)) nx.draw_networkx_edges(g, pos, alpha=0.5) plt.show()
def ped_group(pedgraph, nlist, nscale=600, nalpha=0.95, nsize=15, ealpha=0.2, ewidth=0.3, ecolor="#000000", atName="attr1", atCol=4): ''' Receives a networkx graph and plots. - needs matplotlib package :param pedgraph: networkX graph object (pedigree) :param nscale: scale of the plot :param nalpha: node transparency :param nsize: node size :param ncolor: node color :param ealpha: edge transparency :param ewidth: edge width :param ecolor: edge color :return: ''' grpList = [line.strip() for line in open(nlist, 'r')] part = add_node_attribute("ped_testherd.in", pedgraph, atName=atName, atCol=atCol) values = [part.get(node) for node in grpList] pos = nx.spring_layout(pedgraph, scale=nscale) nx.draw_networkx_nodes(pedgraph, pos, nodelist=grpList, alpha=nalpha, node_color=values, node_size=nsize, linewidths=0.1, cmap=plt.get_cmap('Paired')) # label plot not feasable for larger networks # nx.draw_networkx_labels(pedgraph, pos) # nx.draw_networkx_edges(pedgraph, pos, alpha=ealpha, width=ewidth, edge_color=ecolor) plt.axis("off") plt.show()
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 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, 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 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 malt_demo(nx=False): """ A demonstration of the result of reading a dependency version of the first sentence of the Penn Treebank. """ dg = DependencyGraph("""Pierre NNP 2 NMOD Vinken NNP 8 SUB , , 2 P 61 CD 5 NMOD years NNS 6 AMOD old JJ 2 NMOD , , 2 P will MD 0 ROOT join VB 8 VC the DT 11 NMOD board NN 9 OBJ as IN 9 VMOD a DT 15 NMOD nonexecutive JJ 15 NMOD director NN 12 PMOD Nov. NNP 9 VMOD 29 CD 16 NMOD . . 9 VMOD """) tree = dg.tree() tree.pprint() if nx: # currently doesn't work import networkx from matplotlib import pylab g = dg.nx_graph() g.info() pos = networkx.spring_layout(g, dim=1) networkx.draw_networkx_nodes(g, pos, node_size=50) # networkx.draw_networkx_edges(g, pos, edge_color='k', width=8) networkx.draw_networkx_labels(g, pos, dg.nx_labels) pylab.xticks([]) pylab.yticks([]) pylab.savefig('tree.png') pylab.show()
def initUI(self): scene = QtGui.QGraphicsScene(self) scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex) self.setScene(scene) self.NodeIds = [] self.centrality = [] self.Scene_to_be_updated = scene self.setCacheMode(QtGui.QGraphicsView.CacheBackground) self.setRenderHint(QtGui.QPainter.Antialiasing) self.setInteractive(True) self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter) self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag) i = 0 self.communityPos = nx.nx_pydot.graphviz_layout(self.induced_graph,prog='fdp',args='-Gsep=.25,-GK=20-Eweight=2') # self.communityPos = nx.spring_layout(self.induced_graph,pos=self.Pos,weight='weight',scale=450) for node in self.induced_graph.nodes(): i = i + 1 node_value=Node(self.Graph,i,self.correlationTableObject,True) self.NodeIds.append(node_value) scene.addItem(node_value) x,y=self.communityPos[node] node_value.setPos(x,y) node_value.PutColor(self.clut[i-1]) k =0 for i,j in self.induced_graph.edges(): Weight = self.induced_graph[i][j]['weight'] Edge_Value = 1+(float(Weight-self.Min1)/(self.Max1 - self.Min1))*5 scene.addItem(Edge(self.Graph,self.NodeIds[i],self.NodeIds[j],k, i,j,self.Max,((self.Matrix[j,i]-self.Min1)/(self.Max1 - self.Min1))*5,True)) k = k + 1 self.setSceneRect(self.Scene_to_be_updated.itemsBoundingRect()) self.setScene(self.Scene_to_be_updated) self.fitInView(self.Scene_to_be_updated.itemsBoundingRect(),QtCore.Qt.KeepAspectRatio) self.scaleView(math.pow(2.5, -900 / 1040.0)) self.nodes = [item for item in scene.items() if isinstance(item, Node)] self.edges = [item for item in scene.items() if isinstance(item, Edge)]
def draw_text_graph(G): plt.figure(figsize=(18,12)) pos = nx.spring_layout(G, scale=18) nx.draw_networkx_nodes(G, pos, node_color="white", linewidths=0, node_size=500) nx.draw_networkx_labels(G, pos, font_size=10) nx.draw_networkx_edges(G, pos) plt.xticks([]) plt.yticks([])
def _build_graph(show=False): """Load word dependencies into graph using networkx. Enables easy traversal of dependencies for parsing particular patterns. One graph is created for each sentence. Args: show (bool): If set to True, labeled visualization of network will be opened via matplotlib for each sentence Returns: None: Global variable G is set from within function """ global G G = nx.Graph() node_labels, edge_labels = {}, {} for idx, dep in enumerate(A.deps): types = ["dependent", "governor"] # nodes, labels for x in types: G.add_node(str(dep[x]), word=dep[x + "Gloss"], pos=A.lookup[dep[x]]["pos"]) node_labels[str(dep[x])] = dep[x + "Gloss"] + " : " + A.lookup[dep[x]]["pos"] # edges, labels G.add_edge(str(dep[types[0]]), str(dep[types[1]]), dep=dep["dep"]) edge_labels[(str(dep[types[0]]), str(dep[types[1]]))] = dep["dep"] if show == True: pos = nx.spring_layout(G) nx.draw_networkx(G, pos=pos, labels=node_labels, node_color="white", alpha=.5) nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels) plt.show() ######################################### # Dependency / POS parsing functions #########################################
def Drawcomgraph(G): #Draw the graph pos=nx.spring_layout(G) nx.draw_networkx_edges(G, pos, alpha=0.4) nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif') #colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua' nx.draw_networkx_nodes(G, pos, nodelist=G.nodes(), node_size=150) plt.title("Network Community Analysis") plt.show()
def __init__(self, edges, **kwargs): super().__init__(edges, **kwargs) self.pos = nx.spring_layout(self.G, iterations=100) self.get_measures()
def draw_network(DG): nx.draw_networkx(DG, pos=nx.spring_layout(DG), node_color = 'red') plt.axis('off') # turn off axis plt.savefig('c-elegans.svg') # plt.show()
def centrality(DG): in_degree_centrality = nx.in_degree_centrality(DG) out_degree_centrality = nx.out_degree_centrality(DG) with open('/home/sun/PycharmProjects/Network/in_degree_centrality.csv', 'w') as f: for k, v in in_degree_centrality.items(): f.write(str(k) + ': ' + str(v) + '\n') f.close() with open('/home/sun/PycharmProjects/Network/out_degree_centrality.csv', 'w') as f: for k, v in out_degree_centrality.items(): f.write(str(k) + ': ' + str(v) + '\n') f.close() # def main(): # data = '/home/sun/PycharmProjects/Network/C-elegans-frontal.txt' # # data = 'www.adj' # DG = create_network(data) # # # draw_network(DG) # # clustering_coefficient(DG) # # centrality(DG) # degree_distribution(DG) # # if __name__ == '__main__': # main() # # # DG = nx.DiGraph() # # DG.add_edge(1,2) # # print(DG.edges()) # # # pos = nx.nx_agraph.graphviz_layout(DG) # # nx.draw_networkx(DG, pos = nx.spring_layout(DG)) # # plt.show() # # plt.ishold() # # plt.draw(DG)
def plot_and_save_net(self, picpath='../output/net.png'): net = nx.DiGraph() edge_label = dict() for edge in self.edges: net.add_edge(edge[0], edge[1], weight=1) edge_label[(edge[0], edge[1])] = edge[3] if len(edge_label) > 8: break # edge_label.update({(edge[0], edge[1]) : edge[2]}) pos = nx.spring_layout(net, k=20) # positions for all nodes # nodes nx.draw_networkx_nodes(net, pos, node_size=6000, node_color="green") # edges nx.draw_networkx_edges(net, pos, width=1.5, alpha=0.5, arrows=True, edge_color='black') # labels nx.draw_networkx_labels(net, pos, font_size=20) nx.draw_networkx_edge_labels(net, pos, edge_labels=edge_label, label_pos=0.5, font_family='sans-serif') plt.axis('off') plt.savefig(picpath) # save as png plt.show() # display
def get_reusable_springlayout(network,seed=0): """returns a networkx spring layout function with deterministic behaviour (useful to draw a series of thumbnails)""" rng = RandomState(seed) nodelist = network.nodes() initpos = dict(zip(nodelist,rng.rand(len(nodelist),2))) return lambda net:nx.spring_layout(net,pos=initpos)
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 graph_plot(G, graph_name, nodes_color_fn=_pos_coloring, node_position_path="./data", node_position_file=True, show=True): if node_position_file: spring_pos = pickle.load(open(path_join(node_position_path, graph_name, 'node_pos.bin'), "rb")) else: spring_pos = nx.spring_layout(G) pickle.dump(spring_pos, open(path_join(node_position_path, graph_name, 'node_pos.bin'), "wb")) spring_pos_values = np.array(list(spring_pos.values())) norm_pos = np.linalg.norm(spring_pos_values, axis=1) nodes_color = nodes_color_fn(G, norm_pos) plt.figure(figsize=(5, 5)) plt.axis("off") nx.draw_networkx(G, node_color=nodes_color, pos=spring_pos, camp=plt.get_cmap(CAMP), nodelist=sorted(G.nodes())) if show: plt.show() else: plt.clf() plt.close() return nodes_color