栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python网络图【networkx】极简代码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python网络图【networkx】极简代码

文章目录
  • 安装
  • 简介
  • 示例
    • 无多重边无向图
    • 有多重边有向图
    • 布局
    • 其他算法
  • 附录

2021-4-20更新:

可能新版的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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/833856.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号