# -*- 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())
#消毁图G
G.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'] = 714
G.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 others
nx.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 plt
import re
import networkx as nx
import numpy as np
def 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()