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

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值