安装
Anaconda Prompt下输入conda install networkx
简介
import networkx as nx
# 创建图
# G = nx.Graph() # 无多重边无向图
G = nx.DiGraph() # 无多重边有向图
# G = nx.MultiGraph() # 有多重边无向图
# G = nx.MultiDiGraph() # 有多重边有向图
# 添加节点
G.add_node('a')
# 添加边
G.add_edge('b', 'c')
# 绘图
nx.draw(G, with_labels=True)
绘图参数 | 中文解释 |
---|---|
node_size | 节点的大小 |
node_color | 节点的颜色 |
node_shape | 节点的形状 |
alpha | 透明度 |
width | 边的宽度 |
edge_color | 边的颜色 |
style | 边的样式 |
with_labels | 节点是否带标签 |
font_size | 节点标签字体大小 |
font_color | 节点标签字体颜色 |
示例
无多重边无向图
import jieba, networkx as nx, matplotlib.pyplot as mp
# 分词
jieba.suggest_freq(('人', '美', '波'), True)
text = '大波美人鱼人美波大。奶罩作用是用作罩奶。明天到操场操到天明。床上人客叫客人上床。上海自来水来自海上。'
words = jieba.lcut(text)
# 创建空的网络图
G = nx.Graph()
# 添加节点
for word in words:
G.add_node(word)
# 添加边
for i in range(len(words) - 1):
G.add_edge(words[i], words[i+1])
# 用黑体显示中文
mp.rcParams['font.sans-serif']=['SimHei']
# 绘图
nx.draw(G, alpha=1, with_labels=True, node_color='white', font_size=12)
有多重边有向图
%matplotlib inline
import jieba.posseg as jp, networkx as nx
# 分词
text = '上海自来水来自海上,奶罩作用是用作罩奶,明天到操场操到天明,床上人客叫客人上床。大波美人鱼人美波大。'
words = jp.lcut(text)
# 创建【无多重边有向图】
G = nx.MultiDiGraph() # 有多重边有向图
# 添加节点
for word in words:
G.add_node(word.flag)
# 添加边
for i in range(len(words) - 1):
G.add_edge(words[i].flag, words[i+1].flag)
# 绘图
nx.draw(G, alpha=0.8, with_labels=True, node_color='lightgreen', font_size=36, node_size=999, width=2)