networkx 模型案例

draw函数参数:
      - `node_size`:  指定节点的尺寸大小(默认是300)
      - `node_color`:  指定节点的颜色 (默认是红色,可以用字符串简单标识颜色,例如'r'为红色,'b'为绿色等)
      - `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`: 节点标签字体颜色(默认为黑色)

运用布局:

  circular_layout:节点在一个圆环上均匀分布
  random_layout:节点随机分布
  shell_layout:节点在同心圆上分布
  spring_layout: 用Fruchterman-Reingold算法排列节点(样子类似多中心放射状)
  spectral_layout:根据图的拉普拉斯特征向量排列节点

添加文本:

  用plt.title()方法可以为图形添加一个标题,该方法接受一个字符串作为参数。

  fontsize参数用来指定标题的大小。例如:plt.title("BA Networks", fontsize = 20)。

  如果要在任意位置添加文本,则可以采用plt.text()方法。

 NetworkX提供了4种常见网络的建模方法,分别是:规则图,ER随机图,WS小世界网络和BA无标度网络。

一. 规则图

  规则图差不多是最没有复杂性的一类图,random_graphs.random_regular_graph(d, n)方法可以生成一个含有n个节点,每个节点有d个邻居节点的规则图。

  下面一段示例代码,生成了包含20个节点、每个节点有3个邻居的规则图:

import networkx as nx
import matplotlib.pyplot as plt

# regular graphy
# generate a regular graph which has 20 nodes & each node has 3 neghbour nodes.
RG = nx.random_graphs.random_regular_graph(3, 20)
# the spectral layout
pos = nx.spectral_layout(RG)
# draw the regular graphy
nx.draw(RG, pos, with_labels=False, node_size=30)
plt.show()


 

二、ER随机图

  ER随机图是早期研究得比较多的一类“复杂”网络,模型的基本思想是以概率p连接N个节点中的每一对节点。用random_graphs.erdos_renyi_graph(n,p)方法生成一个含有n个节点、以概率p连接的ER随机图:

import networkx as nx
import matplotlib.pyplot as plt

# erdos renyi graph
# generate a graph which has n=20 nodes, probablity p = 0.2.
ER = nx.random_graphs.erdos_renyi_graph(20, 0.2)
# the shell layout
pos = nx.shell_layout(ER)
nx.draw(ER, pos, with_labels=False, node_size=30)
plt.show()

三、WS小世界网络

  用random_graphs.watts_strogatz_graph(n, k, p)方法生成一个含有n个节点、每个节点有k个邻居、以概率p随机化重连边的WS小世界网络。

  下面是一个例子:

import networkx as nx
import matplotlib.pyplot as plt

# WS network

# generate a WS network which has 20 nodes,
# each node has 4 neighbour nodes,
# random reconnection probability was 0.3.
WS = nx.random_graphs.watts_strogatz_graph(20, 4, 0.3)
# circular layout
pos = nx.circular_layout(WS)
nx.draw(WS, pos, with_labels=False, node_size=30)
plt.show()

四、BA无标度网络

  用random_graphs.barabasi_albert_graph(n, m)方法生成一个含有n个节点、每次加入m条边的BA无标度网络。

  下面是一个例子:

import networkx as nx
import matplotlib.pyplot as plt

# BA scale-free degree network
# generalize BA network which has 20 nodes, m = 1
BA = nx.random_graphs.barabasi_albert_graph(20, 1)
# spring layout
pos = nx.spring_layout(BA)
nx.draw(BA, pos, with_labels=False, node_size=30)
plt.show()

绘制全连接的n边形

spring

shell

import networkx as nx
import matplotlib.pyplot as plt

g = nx.Graph()
node_cnt = 20
g.add_nodes_from(range(node_cnt))
g.add_edges_from([
    (i, j)
    for j in range(node_cnt)
    for i in range(node_cnt)
    if i != j
])

# nx.draw_spring(g, with_labels=True)
nx.draw_shell(g, with_labels=True)
plt.show()

猜你喜欢

转载自my.oschina.net/ahaoboy/blog/1824156
今日推荐