python networkx学习

转自:http://blog.csdn.net/pipisorry/article/details/49839251

其它复杂网络绘图库

[SNAP for python]

[ArcGIS,Python,网络数据集中查询两点最短路径]

Networkx数据类型

Graph types

NetworkX provides data structures and methods for storing graphs.

All NetworkX graph classes allow (hashable) Python objects as nodes.and any Python object can be assigned as an edge attribute.

The choice of graph class depends on the structure of thegraph you want to represent.

使用哪种图形类

Graph TypeNetworkX Class
Undirected SimpleGraph
Directed SimpleDiGraph
With Self-loopsGraph, DiGraph
With Parallel edgesMultiGraph, MultiDiGraph
  • Graph – Undirected graphs with self loops
  • DiGraph - Directed graphs with self loops
  • MultiGraph - Undirected graphs with self loops and parallel edges
  • MultiDiGraph - Directed graphs with self loops and parallel edges
    • Overview
    • Adding and Removing Nodes and Edges
    • Iterating over nodes and edges
    • Information about graph structure
    • Making copies and subgraphs

子图subgraphs

Graph.subgraph(nbunch)

参数nbunch指定子图的节点

返回原图上的子图

[subgraphs]

二分网络

建立二分网络
import networkx
from network.algorithm import bipartite
g.add_edges_from([("nodename1","nodename2"),("nodename3","nodename1")])

判断是否是二分网络
print  bi_partite.is_bipartite(g)

得到两端网络
NSet = nx.bipartite.sets(g) 
Net1 = nx.project(g,NSet[0])
Net2 = nx.project(g,Nset[1])

[Graph types]

皮皮blog



networkx的使用

import networkx as nx

使用Python与NetworkX获取数据:基本使用

>>> import networkx as net
>>> import urllib

NetworkX以图(graph)为基本数据结构。图既可以由程序生成,也可以来自在线数据源,还可以从文件与数据库中读取。
>>> g=net.Graph()  #创建空图
>>> g.add_edge('a','b') #插入一条连接a,b的边到图中,节点将自动插入
>>> g.add_edge('b','c') #再插入一条连接b,c的边
>>> g.add_edge('c','a') #再插入一条连接c,a的边
>>> net.draw(g)         #输出一个三角形的图

你也可以将图的节点与边作为Python列表输出:
>>>> g.nodes() #输出图g的节点值
['a','b','c']
>>>> g.edges() #输出图g的边值
[('a', 'c'), ('a', 'b'), ('c', 'b')]

NetworkX中的图数据结构就像Python的 字典(dict) 一样——一切都能循环,并根据键值读取。
 >>> g.node['a']
 {} 
 >>> g.node['a']['size']=1
 >>> g.node['a']
 {'size' : 1}

节点与边能够存储任意类型字典的属性和任意其他丰富类型的数据:
>>> g['a']  #将临近边及权重作为字典返回输出
{'b': {}, 'c': {}}
>>> g['a']['b']  #返回节点A->B的属性
{}
>>> g['a']['b']['weight']=1  #设置边的属性
>>> g['a']['b']
{'weight' : 1} 

多数的计算社会网络指标也返回一个字典,节点ID作为字典键,指标作为字典的值。你可以像操作任何字典一样操作它们。

[使用Python与NetworkX获取数据]

图Graph

degree(G[, nbunch, weight])Return degree of single node or of nbunch of nodes.
degree_histogram(G)Return a list of the frequency of each degree value.
density(G)Return the density of a graph.
info(G[, n])Print short summary of information for the graph G or the node n.
create_empty_copy(G[, with_nodes])Return a copy of the graph G with all of the edges removed.
is_directed(G)Return True if graph is directed.


节点Nodes

nodes(G)Return a copy of the graph nodes in a list.
number_of_nodes(G)Return the number of nodes in the graph.
nodes_iter(G)Return an iterator over the graph nodes.
all_neighbors(graph, node)Returns all of the neighbors of a node in the graph.
non_neighbors(graph, node)Returns the non-neighbors of the node in the graph.
common_neighbors(G, u, v)Return the common neighbors of two nodes in a graph.


边edges

边相关方法

edges(G[, nbunch])Return list of edges incident to nodes in nbunch.
number_of_edges(G)Return the number of edges in the graph.
edges_iter(G[, nbunch])Return iterator over edges incident to nodes in nbunch.
non_edges(graph)Returns the non-existent edges in the graph.

有序边

target_subgraph.edges()返回的边是无序的。

修改成有序:sortEdges = lambda l: [(n1, n2) if n1 <= n2 else (n2, n1) for n1, n2 in l]

G.number_of_edges()

方法其实是图类的方法G.number_of_edges()

number_of_edges(self, u=None, v=None):
"""Return the number of edges between two nodes


获取属性Attributes

set_node_attributes(G, name, values)Set node attributes from dictionary of nodes and values
get_node_attributes(G, name)Get node attributes from graph
set_edge_attributes(G, name, values)Set edge attributes from dictionary of edge tuples and values.
get_edge_attributes(G, name)Get edge attributes from graph


获取边属性get_edge_attributes(G, name)

返回的是一个key为边的dict

edges_weight_index = nx.get_edge_attributes(target_subgraph, 'weight')
edges_weight_index[(u, v)]

[functions#edges]

添加边

g=net.Graph()  #创建空图

g.add_edge('a','b') #插入一条连接a,b的边到图中,节点将自动插入

批量添加有权边

g.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])

绘制有权图[Weighted Graph]

[Edges]

from: http://blog.csdn.net/pipisorry/article/details/49839251

ref: [Functions]*

[Networkx Reference]*[NetworkX documentation]*[doc NetworkX Examples]*[NetworkX Home]

[NetworkX sourse code download]

[Gallery — NetworkX图形生成源代码]

[sciencenet 复杂网络分析库NetworkX学习笔记]*

[networkx笔记系列]


转自;绘制基本网络图

用matplotlib绘制网络图
基本流程:
1. 导入networkx,matplotlib包
2. 建立网络
3. 绘制网络 nx.draw()
4. 建立布局 pos = nx.spring_layout美化作用
最基本画图程序

import import networkx as nx             #导入networkx包
import matplotlib.pyplot as plt 
G = nx.random_graphs.barabasi_albert_graph(100,1)   #生成一个BA无标度网络G
nx.draw(G)                               #绘制网络G
plt.savefig("ba.png")           #输出方式1: 将图像存为一个png格式的图片文件
plt.show()                            #输出方式2: 在窗口中显示这幅图像 

networkx 提供画图的函数有:

  1. draw(G,[pos,ax,hold])
  2. draw_networkx(G,[pos,with_labels])
  3. draw_networkx_nodes(G,pos,[nodelist]) 绘制网络G的节点图
  4. draw_networkx_edges(G,pos[edgelist]) 绘制网络G的边图
  5. draw_networkx_edge_labels(G, pos[, ...]) 绘制网络G的边图,边有label
    ---有layout 布局画图函数的分界线---
  6. draw_circular(G, **kwargs) Draw the graph G with a circular layout.
  7. draw_random(G, **kwargs) Draw the graph G with a random layout.
  8. draw_spectral(G, **kwargs) Draw the graph G with a spectral layout.
  9. draw_spring(G, **kwargs) Draw the graph G with a spring layout.
  10. draw_shell(G, **kwargs) Draw networkx graph with shell layout.
  11. draw_graphviz(G[, prog]) Draw networkx graph with graphviz layout.

networkx 画图参数:
node_size: 指定节点的尺寸大小(默认是300,单位未知,就是上图中那么大的点)
node_color: 指定节点的颜色 (默认是红色,可以用字符串简单标识颜色,例如'r'为红色,'b'为绿色等,具体可查看手册),用“数据字典”赋值的时候必须对字典取值(.values())后再赋值
node_shape: 节点的形状(默认是圆形,用字符串'o'标识,具体可查看手册)
alpha: 透明度 (默认是1.0,不透明,0为完全透明)
width: 边的宽度 (默认为1.0)
edge_color: 边的颜色(默认为黑色)
style: 边的样式(默认为实现,可选: solid|dashed|dotted,dashdot)
with_labels: 节点是否带标签(默认为True)
font_size: 节点标签字体大小 (默认为12)
font_color: 节点标签字体颜色(默认为黑色)
e.g. nx.draw(G,node_size = 30, with_label = False)
绘制节点的尺寸为30,不带标签的网络图。


布局指定节点排列形式

pos = nx.spring_layout

建立布局,对图进行布局美化,networkx 提供的布局方式有:
- circular_layout:节点在一个圆环上均匀分布
- random_layout:节点随机分布
- shell_layout:节点在同心圆上分布
- spring_layout: 用Fruchterman-Reingold算法排列节点(这个算法我不了解,样子类似多中心放射状)
- spectral_layout:根据图的拉普拉斯特征向量排列节
布局也可用pos参数指定,例如,nx.draw(G, pos = spring_layout(G)) 这样指定了networkx上以中心放射状分布.

绘制划分后的社区

先看一段代码,代码源自site

partition = community.best_partition(User)
size = float(len(set(partition.values())))
pos = nx.spring_layout(G)
count = 0.

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 = 50,
                                node_color = str(count / size))

nx.draw_networkx_edges(User,pos,with_labels = True, alpha=0.5 )
plt.show()

communit.best_partition 是社区划分方法,算法是根据Vincent D.Blondel 等人于2008提出,是基于modularity optimization的heuristic方法.
partition的结果存在字典数据类型:
{'1': 0, '3': 1, '2': 0, '5': 1, '4': 0, '6': 0}
单引号里的数据是key,也就是网络中节点编号。
冒号后面的数值,表示网络中节点的编号属于哪个社区。也就是社区标号。如'6': 0表示6节点属于0社区

 list_nodes = [nodes for nodes in partition.keys()
                                if partition[nodes] == com] 

每次循环list_nodes结果是社区i对应的用户编号。
如第一次循环结果是com = 0, list_nodes= ['1','2','4','6']
第二次循环的结果是com = 1, list_nodes = ['3','6']
这样每次循环,画出一个社区的所有节点:

 nx.draw_networkx_nodes(G, pos, list_nodes, node_size = 50,
                                node_color = str(count / size))

循环结束后通过颜色来标识不同社区

http://segmentfault.com/a/1190000000527216

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值