Python NetworkX 学习笔记

chapter1

快速开始

import networkx as nx
from matplotlib import pyplot as plt

G = nx.Graph() # create a graph object

G.add_node('A') # 一次添加一个节点(这里使用字母作为节点的id)
G.add_nodes_from(['B','C']) # 添加多个节点

G.add_edge('A','B') # 一次添加一条边
G.add_edges_from([('B','C'),('A','C')]) # 一次添加多条
G.add_edges_from([('B', 'D'), ('C', 'E')])
plt.figure(figsize=(7.5,7.5)) # 7.5英寸*7.5英寸
nx.draw_networkx(G)
plt.show()

图像的全局配置

plt.rcParams.update({
	'figure.figsize':(7.5,7.5)
})

chapter2

  • 学习目标
    • Graph:了解无向网络的属性以及它们如何使用NetworkX Graph类表示。
    • Attributes:如何将数据与节点和边关联。
    • Edge Weight:了解如何量化连接强度并为边信息添加注释。
    • DiGraph:了解有向网络的属性以及如何使用NetworkX DiGraph类表示。
    • MultiGraph and MultiDiGraph:了解拥有并行边的网络。

Graph类——无向网络

import networkx as nx
from matplotlib import pyplot as plt

G = nx.karate_club_graph()
karate_pos = nx.spring_layout(G,k = 0.3) # 节点直接通过一条边连接,将会靠的更近
plt.figure()
nx.draw_networkx(G,karate_pos)
plt.show()

Graph类提供了许多节点和边进行交互的方法:

  • 获取节点和边的属性的迭代器
list(G.nodes) # [0,1,2...]
list(G.edges) # [(0,1),(0,2)...]
  • 判断节点或边是否存在(根据id匹配)
hyh = 0
hyh in G # True
G.has_node(hyh) #True
member_id = 1
(hyh,member_id) in G.edges #True
G.has_edge(hyh,member_id) #True
  • 获取节点的邻居,通常,通过一条边连接到某个特定节点的节点集称为该节点的邻居。
list(G.neighbors(hyh)) #[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31]

为节点和边添加属性

有时候,网络节点和边缘被附加了额外的信息。在Graph类中,每个节点和边都可以有一组属性来存储这些附加信息。属性可以简单地作为存储与节点和边相关的信息的方便场所,也可以用于可视化和网络算法。

Graph类允许您向节点添加任意数量的属性。对于网络G,每个节点的属性都存储在G处的dict中。节点[v],其中v是节点的ID。

  • 遍历节点,添加club属性
member_club = [
    0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
    0, 0, 0, 0, 1, 1, 0, 0, 1, 0,
    1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1]
for node_id in G.nodes:
    G.nodes[node_id]["club"] = member_club[node_id]
G.add_node(11, club=0)
  • 定制节点的颜色
node_color = [
    '#1f78b4' if G.nodes[v]["club"] == 0
    else '#33a02c' for v in G]
nx.draw_networkx(G, karate_pos, label=True, node_color=node_color)

  • 遍历边
# Iterate through all edges
for v, w in G.edges:
    # Compare `club` property of edge endpoints
    # Set edge `internal` property to True if they match
    if G.nodes[v]["club"] == G.nodes[w]["club"]: # 两个节点直接存在联系
        G.edges[v, w]["internal"] = True
    else:
        G.edges[v, w]["internal"] = False

internal = [e for e in G.edges if G.edges[e]["internal"]] # 存在联系的数组
external = [e for e in G.edges if not G.edges[e]["internal"]]

# Draw nodes and node labels  多个线样式,需要绘制多次
nx.draw_networkx_nodes(G, karate_pos, node_color=node_color)
nx.draw_networkx_labels(G, karate_pos)
# Draw internal edges as solid lines
nx.draw_networkx_edges(G, karate_pos, edgelist=internal)
# Draw external edges as dashed lines
nx.draw_networkx_edges(G, karate_pos, edgelist=external, style="dashed")# 虚线

为边增加权重

定义计算边权重的函数

def tie_strength(G, v, w):
    # Get neighbors of nodes v and w in G
    v_neighbors = set(G.neighbors(v))
    w_neighbors = set(G.neighbors(w))
    # Return size of the set intersection
    return 1 + len(v_neighbors & w_neighbors) # 交集大小

遍历每条边,计算权重

for v, w in G.edges: 
    G.edges[v, w]["weight"] = tie_strength(G, v, w)
# Store weights in a list
edge_weights = [G.edges[v, w]["weight"] for v, w in G.edges]

将边权值传递给spring_layout(),将强连接的节点推的更近。

# 将边权值传递给spring_layout(),将强连接节点推得更近
weighted_pos = nx.spring_layout(G, pos=karate_pos, k=0.3, weight="weight")

# Draw network with edge color determined by weight
nx.draw_networkx(
    G, weighted_pos, width=8, node_color=node_color,
    edge_color=edge_weights, edge_vmin=0, edge_vmax=6, edge_cmap=plt.cm.Blues)
# Draw solid/dashed lines on top of internal/external edges
nx.draw_networkx_edges(G, weighted_pos, edgelist=internal, edge_color="gray")
nx.draw_networkx_edges(G, weighted_pos, edgelist=external, edge_color="gray", style="dashed")

有向图

这次从gxef中读取数据,类型是directed有向图,每条边都包含source和target。

<?xml version='1.0' encoding='utf-8'?>
<gexf version="1.2" xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance">
  <graph defaultedgetype="directed" mode="static" name="">
    <meta>
      <creator>NetworkX 2.2rc1.dev_20181126202121</creator>
      <lastmodified>26/11/2018</lastmodified>
    </meta>
    <nodes>
      <node id="0" label="0" />
      <node id="2" label="2" />
        	  <!-- 省略 -->
    </nodes>
    <edges>
      <edge id="0" source="0" target="2" />
      <edge id="1" source="0" target="5" />
	  <!-- 省略 -->
    </edges>
  </graph>
</gexf>

读取文件中的数据,画出图形。

G = nx.read_gexf("data/knecht2008/klas12b-net-1.gexf",node_type=int)
student_pos = nx.spring_layout(G, k=1.5)
nx.draw_networkx(G, student_pos, arrowsize=20)

获取节点邻居,后继,前驱。

list(G.neighbors(20))
list(G.successors(20))
list(G.predecessors(20))

有向图转化为无向图

# Create undirected copies of G
G_either = G.to_undirected() # 默认情况下, 只要存在一个方向,就连接
G_both = G.to_undirected(reciprocal=True) # 两个方向都存在的时候,才会创建
# Set up a figure
plt.figure(figsize=(10,5))
# Draw G_either on left
plt.subplot(1, 2, 1)
nx.draw_networkx(G_either, student_pos)
# Draw G_both on right
plt.subplot(1, 2, 2)
nx.draw_networkx(G_both, student_pos)

并行边

例:A点到B点有许多条路

G = nx.MultiGraph()
G.add_edges_from([
    ("North Bank", "Kneiphof", {"bridge": "Krämerbrücke"}),
    ("North Bank", "Kneiphof", {"bridge": "Schmiedebrücke"}),
    ("North Bank", "Lomse",    {"bridge": "Holzbrücke"}),
    ("Lomse",      "Kneiphof", {"bridge": "Dombrücke"}),
    ("South Bank", "Kneiphof", {"bridge": "Grüne Brücke"}),
    ("South Bank", "Kneiphof", {"bridge": "Köttelbrücke"}),
    ("South Bank", "Lomse",    {"bridge": "Hohe Brücke"})
])

list(G.edges)[0] # ('North Bank', 'Kneiphof', 0)
G.edges['North Bank', 'Kneiphof', 0] # {'bridge': 'Krämerbrücke'}
posted @ 2020-09-04 22:25  天乔巴夏丶  阅读(1399)  评论(0编辑  收藏  举报