更新:可能新版的networkx不能直接出图,那就在代码末尾加两行代码,就可以出图了
- import matplotlib.pyplot as mp
- mp.show()
-
以下为原文:
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)
-
参数 | 解释 |
---|---|
circular_layout | 节点在一个圆环上均匀分布 |
random_layout | 节点随机分布 |
shell_layout | 节点在同心圆上分布 |
spring_layout | 用Fruchterman-Reingold算法排列节点 |
- nx.draw(G, pos=nx.shell_layout(G), alpha=0.8, with_labels=True, node_color='lightgreen', font_size=36, node_size=999, width=2)
-
函数 | 功能 |
---|---|
nx.shortest_path_length | 最短距离 |
nx.shortest_path | 最短路径 |
nx.pagerank | 网页排名 |
GitHub地址:
https://github.com/AryeYellow/PyProjects/blob/master/DataScience/Visualization.ipynb