networkx绘制网络关系图

1、用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: 在窗口中显示这幅图像 

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.

3、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,不带标签的网络图。


4、布局指定节点排列形式

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上以中心放射状分布.

5、按权重划分为重权值得边和轻权值的边

elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5]
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5]

6、将Matplotlib图形保存为全屏图像

manager = plt.get_current_fig_manager()
manager.window.showMaximized()

7、分图:

plt.figure(1, figsize=(9, 3))
plt.figure(2, figsize=(9, 3))
 

猜你喜欢

转载自www.cnblogs.com/rnanprince/p/10816771.html
今日推荐