python-networkx模块

来源:互联网 发布:2016网络写手收入排行 编辑:程序博客网 时间:2024/05/01 22:53
# -*- coding: utf-8 -*-__author__ = 'zzw'import networkx as nx'''G = nx.Graph()G.add_node(1)  #添加点G.add_nodes_from([2, 3])  #添加一个列表H = nx.path_graph(10)    #添加一个迭代器G.add_nodes_from(H)#既然G包含H作为点。你也可以把图H当做图G中的点G.add_node(H)#边G.add_edge(1, 2)e = (1, 2)G.add_edge(*e)G.add_nodes_from([(1, 2), (1, 3)])#也可以是(2, 3, {'weight': 3.14})#也可以添加迭代器G.add_nodes_from(H.edges())#消毁图GG.remove_node()G.remove_nodes_from()G.remove_edge()G.remove_edges_from()G.remove_node(H)G.clear()g = nx.Graph()g.add_edges_from([(1, 2), (1, 3)])g.add_node(1)g.add_edge(1, 2)g.add_node('spam')g.add_nodes_from('spam')#迭代器print g.nodes()print g.edges()print g.neighbors(1)H = nx.DiGraph(g)   #有向图print H.edges()H.clear()edgelist = [(0, 1), (1, 2), (2, 3)]H = nx.Graph(edgelist)H = nx.DiGraph(H)print H.edges()#对于无向图FG=nx.Graph()FG.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])for n,nbrs in FG.adjacency_iter():    for nbr,eattr in nbrs.items():        data=eattr['weight']        print '(%d, %d, %.3f)' % (n,nbr,data)#图的属性G = nx.Graph(day="Friday")print G.graph#{'day': 'Friday'}#或者G.graph['day'] = 'Monday'print G.graph#点的属性G.add_node(1, time='5pm')G.add_nodes_from([3], time='2pm')G.node[1]#{’time’: ’5pm’}G.node[1]['room'] = 714G.nodes(data=True)#[(1, {’room’: 714, ’time’: ’5pm’}), (3, {’time’: ’2pm’})]#边的属性>>> G.add_edge(1, 2, weight=4.7 )>>> G.add_edges_from([(3,4),(4,5)], color=’red’)>>> G.add_edges_from([(1,2,{’color’:’blue’}), (2,3,{’weight’:8})])>>> G[1][2][’weight’] = 4.7>>> G.edge[1][2][’weight’] = 4#有向图dg = nx.DiGraph()dg.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75), (1, 3, 0.7)])print dg.out_degree(1, weight='weight')#1.2    点1所有出去边上的权值和print dg.degree(1, weight='weight')#1.95    点1出边和入边的权值和print dg.out_degree(1)   #1的出度print dg.in_degree(1)    #1的入度print dg.successors(1)   #1的继承者print dg.neighbors(1)   #1的邻居print dg.predecessors(1)  #1的父亲#一些方法subgraph(G, nbunch)   G在迭代器nbunch上的子图union(G1,G2)          并集disjoint_union(G1,G2)  图上所有点都不同的并集cartesian_product(G1,G2) 笛卡尔积compose(G1,G2)        识别图中相同的元素complement(G)            补图create_empty_copy(G)convert_to_undirected(G) 返回无向图convert_to_directed(G)   有向图#读写文件#Reading a graph stored in a file using common graph formats, such as#  edge lists,# adjacency lists,   邻接矩阵#GraphML,#  pickle,#  LEDA and othersnx.write_gml(red, "path")my_graph = nx.read_gml("path")'''G = nx.DiGraph()G.add_edges_from([(1, 2), (1, 3)])G.add_node("spam")import matplotlib.pyplot as plt#nx.draw(G)#nx.draw_random(G)nx.draw_spectral(G)print G.out_degree()print type(G.out_degree())for v , u in G.out_degree().iteritems():    print u#nx.draw()nx.draw(G,pos=nx.spectral_layout(G), nodecolor='r',edge_color='b')#plt.show()

一个例子:

# -*- coding: utf-8 -*-__author__ = 'zzw'import matplotlib.pyplot as pltimport reimport networkx as nximport numpy as npdef plot():    G = nx.DiGraph()    with open('C:\IC_Para.txt', 'rb') as f:        lines = f.readlines()        G.add_weighted_edges_from([re.sub(r'(->|:\s+)', ',', line).split(',') for line in lines])    degree = G.out_degree()#计算节点的出度    edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())    weights = list(weights)    pos = nx.spring_layout(G) #设置网络的布局    fig = plt.figure(figsize=(10, 8), facecolor='white')    nx.draw(G, pos, nodelist=[key for key, value in degree.iteritems() if value > 1],            node_size=[np.sqrt(v + 1) * 8 for v in (degree.values())], node_color='tomato',            node_shape='o', cmap=plt.cm.gray,            edgelist=edges, edge_color='b', width=map(lambda x: float(x) * 2.0, weights),            with_labels=False, arrows=False)    plt.savefig("c:\\graph.png")plot()

这里写图片描述

0 0