python networkx 包绘制复杂网络关系图的实现


Posted in Python onJuly 10, 2019

1. 创建一个图

import networkx as nx
g = nx.Graph()
g.clear() #将图上元素清空

所有的构建复杂网络图的操作基本都围绕这个g来执行。

2. 节点

节点的名字可以是任意数据类型的,添加一个节点是

g.add_node(1)
g.add_node("a")
g.add_node("spam")

添加一组节点,就是提前构建好了一个节点列表,将其一次性加进来,这跟后边加边的操作是具有一致性的。

g.add_nodes_from([2,3])
or 
a = [2,3]
g.add_nodes_from(a)

这里需要值得注意的一点是,对于add_node加一个点来说,字符串是只添加了名字为整个字符串的节点。但是对于

add_nodes_from加一组点来说,字符串表示了添加了每一个字符都代表的多个节点,exp:
g.add_node("spam") #添加了一个名为spam的节点
g.add_nodes_from("spam") #添加了4个节点,名为s,p,a,m
g.nodes() #可以将以上5个节点打印出来看看

加一组从0开始的连续数字的节点

H = nx.path_graph(10)
g.add_nodes_from(H) #将0~9加入了节点
#但请勿使用g.add_node(H)

删除节点

与添加节点同理

g.remove_node(node_name)
g.remove_nodes_from(nodes_list)

3. 边

边是由对应节点的名字的元组组成,加一条边

g.add_edge(1,2)
e = (2,3)
g.add_edge(*e) #直接g.add_edge(e)数据类型不对,*是将元组中的元素取出

加一组边

g.add_edges_from([(1,2),(1,3)])
g.add_edges_from([("a","spam") , ("a",2)])

通过nx.path_graph(n)加一系列连续的边

n = 10
H = nx.path_graph(n)
g.add_edges_from(H.edges()) #添加了0~1,1~2 ... n-2~n-1这样的n-1条连续的边

删除边

同理添加边的操作

g.remove_edge(edge)
g.remove_edges_from(edges_list)

4. 查看图上点和边的信息

g.number_of_nodes() #查看点的数量
g.number_of_edges() #查看边的数量
g.nodes() #返回所有点的信息(list)
g.edges() #返回所有边的信息(list中每个元素是一个tuple)
g.neighbors(1) #所有与1这个点相连的点的信息以列表的形式返回
g[1] #查看所有与1相连的边的属性,格式输出:{0: {}, 2: {}} 表示1和0相连的边没有设置任何属性(也就是{}没有信息),同理1和2相连的边也没有任何属性

method explanation
Graph.has_node(n) Return True if the graph contains the node n.
Graph.__contains__(n) Return True if n is a node, False otherwise.
Graph.has_edge(u, v) Return True if the edge (u,v) is in the graph.
Graph.order() Return the number of nodes in the graph.
Graph.number_of_nodes() Return the number of nodes in the graph.
Graph.__len__() Return the number of nodes.
Graph.degree([nbunch, weight]) Return the degree of a node or nodes.
Graph.degree_iter([nbunch, weight]) Return an iterator for (node, degree).
Graph.size([weight]) Return the number of edges.
Graph.number_of_edges([u, v]) Return the number of edges between two nodes.
Graph.nodes_with_selfloops() Return a list of nodes with self loops.
Graph.selfloop_edges([data, default]) Return a list of selfloop edges.
Graph.number_of_selfloops() Return the number of selfloop edges.

5. 图的属性设置

为图赋予初始属性

g = nx.Graph(day="Monday") 
g.graph # {'day': 'Monday'}

修改图的属性

g.graph['day'] = 'Tuesday'
g.graph # {'day': 'Tuesday'}

6. 点的属性设置

g.add_node('benz', money=10000, fuel="1.5L")
print g.node['benz'] # {'fuel': '1.5L', 'money': 10000}
print g.node['benz']['money'] # 10000
print g.nodes(data=True) # data默认false就是不输出属性信息,修改为true,会将节点名字和属性信息一起输出

7. 边的属性设置

通过上文中对g[1]的介绍可知边的属性在{}中显示出来,我们可以根据这个秀改变的属性

g.clear()
n = 10
H = nx.path_graph(n)
g.add_nodes_from(H)
g.add_edges_from(H.edges())
g[1][2]['color'] = 'blue'

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

8. 不同类型的图(有向图Directed graphs , 重边图 Multigraphs)

Directed graphs

DG = nx.DiGraph()
DG.add_weighted_edges_from([(1,2,0.5), (3,1,0.75), (1,4,0.3)]) # 添加带权值的边
print DG.out_degree(1) # 打印结果:2 表示:找到1的出度
print DG.out_degree(1, weight='weight') # 打印结果:0.8 表示:从1出去的边的权值和,这里权值是以weight属性值作为标准,如果你有一个money属性,那么也可以修改为weight='money',那么结果就是对money求和了
print DG.successors(1) # [2,4] 表示1的后继节点有2和4
print DG.predecessors(1) # [3] 表示只有一个节点3有指向1的连边

Multigraphs

简答从字面上理解就是这种复杂网络图允许你相同节点之间允许出现重边

MG=nx.MultiGraph()
MG.add_weighted_edges_from([(1,2,.5), (1,2,.75), (2,3,.5)])
print MG.degree(weight='weight') # {1: 1.25, 2: 1.75, 3: 0.5}
GG=nx.Graph()
for n,nbrs in MG.adjacency_iter():
 for nbr,edict in nbrs.items():
  minvalue=min([d['weight'] for d in edict.values()])
  GG.add_edge(n,nbr, weight = minvalue)

print nx.shortest_path(GG,1,3) # [1, 2, 3]

9.  图的遍历

g = nx.Graph()
g.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])
for n,nbrs in g.adjacency_iter(): #n表示每一个起始点,nbrs是一个字典,字典中的每一个元素包含了这个起始点连接的点和这两个点连边对应的属性
 print n, nbrs
 for nbr,eattr in nbrs.items():
  # nbr表示跟n连接的点,eattr表示这两个点连边的属性集合,这里只设置了weight,如果你还设置了color,那么就可以通过eattr['color']访问到对应的color元素
  data=eattr['weight']
  if data<0.5: print('(%d, %d, %.3f)' % (n,nbr,data))

10. 图生成和图上的一些操作

下方的这些操作都是在networkx包内的方法

subgraph(G, nbunch)  - induce subgraph of G on nodes in nbunch
union(G1,G2)    - graph union
disjoint_union(G1,G2) - graph union assuming all nodes are different
cartesian_product(G1,G2) - return Cartesian product graph
compose(G1,G2)   - combine graphs identifying nodes common to both
complement(G)   - graph complement
create_empty_copy(G)  - return an empty copy of the same graph class
convert_to_undirected(G) - return an undirected representation of G
convert_to_directed(G) - return a directed representation of G

11. 图上分析

g = nx.Graph()
g.add_edges_from([(1,2), (1,3)])
g.add_node("spam") 
nx.connected_components(g) # [[1, 2, 3], ['spam']] 表示返回g上的不同连通块
sorted(nx.degree(g).values())

通过构建权值图,可以直接快速利用dijkstra_path()接口计算最短路程

>>> G=nx.Graph()
>>> e=[('a','b',0.3),('b','c',0.9),('a','c',0.5),('c','d',1.2)]
>>> G.add_weighted_edges_from(e)
>>> print(nx.dijkstra_path(G,'a','d'))
['a', 'c', 'd']

12. 图的绘制

下面是4种图的构造方法,选择其中一个

nx.draw(g)
nx.draw_random(g) #点随机分布
nx.draw_circular(g) #点的分布形成一个环
nx.draw_spectral(g)

最后将图形表现出来

import matplotlib.pyplot as plt
plt.show()

将图片保存到下来

nx.draw(g)
plt.savefig("path.png")

修改节点颜色,边的颜色

g = nx.cubical_graph()
nx.draw(g, pos=nx.spectral_layout(g), nodecolor='r', edge_color='b')
plt.show()

13. 图形种类的选择

Graph Type NetworkX Class
简单无向图 Graph()
简单有向图 DiGraph()
有自环 Grap(),DiGraph()
有重边 MultiGraph(), MultiDiGraph()

reference:https://networkx.github.io/documentation/networkx-1.10/reference/classes.html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现读取邮箱中的邮件功能示例【含文本及附件】
Aug 05 Python
对Python中range()函数和list的比较
Apr 19 Python
python实现单链表中删除倒数第K个节点的方法
Sep 28 Python
Python小白必备的8个最常用的内置函数(推荐)
Apr 03 Python
NumPy 基本切片和索引的具体使用方法
Apr 24 Python
PyTorch的深度学习入门教程之构建神经网络
Jun 27 Python
python超时重新请求解决方案
Oct 21 Python
python 调试冷知识(小结)
Nov 11 Python
opencv-python 读取图像并转换颜色空间实例
Dec 09 Python
python3实现将json对象存入Redis以及数据的导入导出
Jul 16 Python
详解python中的闭包
Sep 07 Python
python 如何对logging日志封装
Dec 02 Python
python卸载后再次安装遇到的问题解决
Jul 10 #Python
Python求离散序列导数的示例
Jul 10 #Python
Python Matplotlib 基于networkx画关系网络图
Jul 10 #Python
我们为什么要减少Python中循环的使用
Jul 10 #Python
详解Python中的各种转义符\n\r\t
Jul 10 #Python
使用python画社交网络图实例代码
Jul 10 #Python
python 绘制拟合曲线并加指定点标识的实现
Jul 10 #Python
You might like
PHP和Mysqlweb应用开发核心技术 第1部分 Php基础-3 代码组织和重用2
2011/07/03 PHP
PHP中IP地址与整型数字互相转换详解
2014/08/20 PHP
php的socket编程详解
2016/11/20 PHP
javascript之函数直接量(function(){})()
2007/06/29 Javascript
jQuery 全选效果实现代码
2009/03/23 Javascript
ExtJS 2.2.1的grid控件在ie6中的显示问题
2009/05/04 Javascript
JavaScript 类似flash效果的立体图片浏览器
2010/02/08 Javascript
jquery ready()的几种实现方法小结
2010/06/18 Javascript
js中opener与parent的区别详细解析
2014/01/14 Javascript
js判断当前浏览器类型,判断IE浏览器方法
2014/06/02 Javascript
轻松创建nodejs服务器(10):处理POST请求
2014/12/18 NodeJs
jQuery基于扩展实现的倒计时效果
2016/05/14 Javascript
jQuery Ajax全解析
2017/02/13 Javascript
原生js实现放大镜特效
2017/03/08 Javascript
基于jQuery实现手风琴菜单、层级菜单、置顶菜单、无缝滚动效果
2017/07/20 jQuery
4 种滚动吸顶实现方式的比较
2019/04/09 Javascript
Vue动态组件和异步组件原理详解
2019/05/06 Javascript
vue实现按需加载组件及异步组件功能
2019/05/27 Javascript
vue transition 在子组件中失效的解决
2019/11/12 Javascript
[00:48]食人魔魔法师至宝“金鹏之幸”全新模型和自定义特效展示
2019/12/19 DOTA
Python多进程编程技术实例分析
2014/09/16 Python
在Gnumeric下使用Python脚本操作表格的教程
2015/04/14 Python
Python中几个比较常见的名词解释
2015/07/04 Python
使用python加密自己的密码
2015/08/04 Python
python excel转换csv代码实例
2019/08/26 Python
python__new__内置静态方法使用解析
2020/01/07 Python
Python中pyecharts安装及安装失败的解决方法
2020/02/18 Python
python使用bs4爬取boss直聘静态页面
2020/10/10 Python
幼师求职自荐信
2014/05/31 职场文书
煤矿安全知识竞赛活动总结
2014/07/07 职场文书
考试保密承诺书
2014/08/30 职场文书
2014幼儿教师个人工作总结
2014/12/03 职场文书
2015年银行工作总结范文
2015/04/01 职场文书
幼儿园家长反馈意见
2015/06/03 职场文书
预备党员入党感想
2015/08/10 职场文书
MySQL索引知识的一些小妙招总结
2021/05/10 MySQL