Python networkx 筆記

Python networkx 筆記

NetworkX 用於建立網絡模型、繪製網路圖、分析網絡結構等等的算法以及一些基本的繪圖工具。

創建 Graph

networkx 有四種圖,分別為無向圖、有向圖、多重邊無向圖、多重邊有向圖。

1
2
3
4
5
6
7
import networkx as nx

# 創建空網路圖
G = nx.Graph()
G = nx.DiGraph()
G = nx.MultiGraph()
G = nx.MultiDiGraph()

添加節點

1
2
G.add_node('A')
G.add_nodes_from(['B','C'])

添加邊與權重

1
2
3
4
5
G.add_edge('A', 'D', weight=0.8)
G.add_edges_from([
('B','C', {'weight': 0.3}),
('C','A', {'weight': 0.6})
])

刪除

1
2
3
4
5
6
7
8
# 刪除節點
G.remove_node('BC')

# 刪除邊
G.remove_edge('A', 'D')

# 刪除所有節點與邊
G.clear()

另外也可以從 DataFrame 載入

1
2
3
4
5
6
7
8
9
10
11
import pandas as pd

df = pd.DataFrame(
[('A', 'D', 0.3),
('A', 'B', 0.7),
('B', 'E', 0.6),
('C', 'E', 0.2),
('D', 'E', 0.2)],
columns=['src', 'dst', 'weight']
)
G = nx.from_pandas_edgelist(df, 'src', 'dst', edge_attr='weight')

繪圖 nx.draw()

需要使用 matplotlib

1
2
3
4
import matplotlib.pyplot as plt

nx.draw(G)
plt.show()

詳解 nx.draw()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
G: networkx 圖

pos: 佈局指定節點排列形式

node_size: 節點大小(預設300)

node_color: 節點顏色(預設紅色)

node_shape: 節點形狀(預設o)

alpha: 透明度(預設1.0 不透明, 0為完全透明)

width: 邊線的寬度(預設1.0)

edge_color: 邊線顏色(預設黑色)

style: 邊線的樣式(solid|dashed|dotted|dashdot)

with_labels: 節點是否帶標籤

font_size: 標籤字體大小(預設12)

font_color: 標籤字體顏色(預設黑色)

pos

1
2
3
4
5
nx.random_layout:隨機分佈
nx.circular_layout:節點在圓環上均勻分佈
nx.shell_layout:節點在同心圓上分佈
nx.spring_layout: 用 Fruchterman-Reingold 演算法排列節點
nx.spectral_layout:根據圖的拉普拉斯特徵向量排列節

範例:

1
2
3
4
5
6
7
8
9
10
11
12
plt.figure(1, figsize=(8,8))
nx.draw(
G,
pos=nx.spring_layout(G),
node_color='b',
edge_color='r',
with_labels=True,
font_size=15,
node_size=40,
width=0.7
)
plt.show()

評論