networkX-01-基础

文章目录

教程仓库地址:github networkx_tutorial

创建一个图

  • Graph是由一组节点和节点对(边)组成的。
python 复制代码
# 创建一个没有节点和边的空图。
import networkx as nx
G = nx.Graph()

1. 节点

  • 图G可由多种方式生成。NetWorkX中包含许多图形生成函数(graph generator functions),用于读取和写入多种格式的图形。

方式1 :一次添加一个节点

python 复制代码
G.add_node(1)
G.add_node(2)
nx.draw(G=G,with_labels=True)   # 


方式2:从list中添加节点

  • 一次性添加多个节点
  • 在Networkx中,节点可以是int、str、xml、另外一个Graph
python 复制代码
# G = nx.Graph()
nodes_list = ['a','1']  # 注意 str 和 int
G.add_nodes_from(nodes_list)
nx.draw(G=G,with_labels=True)  


方式3:添加节点时附加节点属性字典

  • node_attribute_dict 通常用于存储节点及其相应的属性。在这个字典中,键代表节点的标识符,而值则是另一个包含该节点各种属性的字典。
python 复制代码
# node_attribute_dict 样式如下:
[
  ('节点1', {'属性1': '值1', '属性2': '值2'}),
  ('节点2', {'属性1': '值3', '属性2': '值4'}),
  ('节点3', {'属性1': '值5', '属性2': '值6'})
]
复制代码
[('节点1', {'属性1': '值1', '属性2': '值2'}),
 ('节点2', {'属性1': '值3', '属性2': '值4'}),
 ('节点3', {'属性1': '值5', '属性2': '值6'})]
python 复制代码
node_attributes_dict = [
    (4,{"color": "red"}),
    (5,{"color": "green"}),
]

G.add_nodes_from(node_attributes_dict)
nx.draw(G=G,with_labels=True)  


方式4:将一个图中的节点合并到另外一个图中

python 复制代码
# 使用path_graph()创建一个图H
H = nx.path_graph(10)
# 将H中的节点添加到G中
G.add_nodes_from(H)
nx.draw(G=G,with_labels=True)  


2. 边

方式1:一次添加一条边

  • add_edge()
python 复制代码
G.add_edge(1,5)
nx.draw(G=G,with_labels=True)  


python 复制代码
e = (2, 3)  
G.add_edge(*e) # 在Python中,*运算符用于解包元组、列表或其他可迭代对象。 等同于G.add_edge(2,3)
nx.draw(G=G,with_labels=True)  


方式2:列表(list)

  • 边元祖
    • (u,v)
    • (u,v,{'weight':3.1415}) ,u,v后面跟着的是边属性字典 (edge attribute dict)
python 复制代码
# (u,v)
edges_list = [(1,2),(1,4)]
G.add_edges_from(edges_list)
nx.draw(G=G,with_labels=True) 


方式3:从另外一个G添加边

python 复制代码
G.add_edges_from(H.edges)
nx.draw(G=G,with_labels=True) 


方式4:使用边属性字典添加边属性

python 复制代码
# 定义边属性字典
edge_attributes_dict = {
    (1, 2): 1,
    (2, 3): 2,
    (3, 4): 1.5,
    (4, 5): 2.5
}
nx.set_edge_attributes(G=G,values = edge_attributes_dict,name = 'weight') 
nx.draw(G=G,with_labels=True) 


3. 节点视图、边视图

python 复制代码
G.edges(data = True)
复制代码
EdgeDataView([(1, 5, {}), (1, 2, {'weight': 1}), (1, 4, {}), (1, 0, {}), (2, 3, {'weight': 2}), (4, 3, {'weight': 1.5}), (4, 5, {'weight': 2.5}), (5, 6, {}), (6, 7, {}), (7, 8, {}), (8, 9, {})])
python 复制代码
type(G.nodes())
复制代码
networkx.classes.reportviews.NodeView
python 复制代码
# 查看网络中的节点
list(G.nodes(data = True))
复制代码
[(1, {}),
 (2, {}),
 ('a', {}),
 ('1', {}),
 (4, {'color': 'red'}),
 (5, {'color': 'green'}),
 (0, {}),
 (3, {}),
 (6, {}),
 (7, {}),
 (8, {}),
 (9, {})]
python 复制代码
# 指定属性进行查看
list(G.nodes(data = 'color'))
复制代码
[(1, None),
 (2, None),
 ('a', None),
 ('1', None),
 (4, 'red'),
 (5, 'green'),
 (0, None),
 (3, None),
 (6, None),
 (7, None),
 (8, None),
 (9, None)]
python 复制代码
# 查看网络中的边
list(G.edges(data = True))
复制代码
[(1, 5, {}),
 (1, 2, {'weight': 1}),
 (1, 4, {}),
 (1, 0, {}),
 (2, 3, {'weight': 2}),
 (4, 3, {'weight': 1.5}),
 (4, 5, {'weight': 2.5}),
 (5, 6, {}),
 (6, 7, {}),
 (7, 8, {}),
 (8, 9, {})]

4. 移除边、节点

python 复制代码
G.remove_node('a')
# G.remove_nodes_from([1,2,3])
list(G.edges(data = True))
复制代码
[(1, 5, {}),
 (1, 2, {'weight': 1}),
 (1, 4, {}),
 (1, 0, {}),
 (2, 3, {'weight': 2}),
 (4, 3, {'weight': 1.5}),
 (4, 5, {'weight': 2.5}),
 (5, 6, {}),
 (6, 7, {}),
 (7, 8, {}),
 (8, 9, {})]

5. 可视化

基于节点属性

  • 在这个例子中,我们使用node_attributes_dict来存储节点4和节点5的颜色属性。
  • 我们通过G.add_nodes_from(node_attributes_dict)将节点及其属性添加到图G中。
  • 然后,使用nx.draw(G=G, with_labels=True)进行图的可视化,其中节点标签会显示。
python 复制代码
# 基于节点的color属性为节点着色
G.nodes(data = 'color') 
复制代码
NodeDataView({1: None, 2: None, '1': None, 4: 'red', 5: 'green', 0: None, 3: None, 6: None, 7: None, 8: None, 9: None}, data='color')
python 复制代码
# 根据节点属性设置节点颜色
node_colors = [data.get('color', 'blue') for node,data in G.nodes(data = True)]
node_colors
复制代码
['blue',
 'blue',
 'blue',
 'red',
 'green',
 'blue',
 'blue',
 'blue',
 'blue',
 'blue',
 'blue']
python 复制代码
nx.draw(G=G,with_labels=True,node_color = node_colors)  


基于边属性

python 复制代码
# 1.获取边属性
edge_weights = nx.get_edge_attributes(G, 'weight')
edge_weights
复制代码
{(1, 2): 1, (2, 3): 2, (4, 3): 1.5, (4, 5): 2.5}
python 复制代码
# 2.自定义边的可视化样式,下面是基于weight来设置边的宽度 
edge_widths = [edge_weights.get((u, v), 1) for u, v in G.edges()]  # 1为默认宽度
edge_widths
复制代码
[1, 1, 1, 1, 2, 1.5, 2.5, 1, 1, 1, 1]
python 复制代码
# 3.可视化
nx.draw(G=G,with_labels=True,node_color = node_colors, width=edge_widths)


python 复制代码
# 也可以设置为权重的倍数
edge_widths = [2*edge_weights.get((u, v), 1) for u, v in G.edges()]  # 1为默认宽度
edge_widths
复制代码
[2, 2, 2, 2, 4, 3.0, 5.0, 2, 2, 2, 2]
python 复制代码
# 3.可视化
nx.draw(G=G,with_labels=True,node_color = node_colors, width=edge_widths)


6. 有向图的构建

  • DiGraph---Directed graphs with self loops
  • nx.DiGraph
python 复制代码
G_2 = nx.DiGraph()
edges_list = [(1, 2), (1, 3), (1, 4), (3, 4)]
G_2.add_edges_from(edges_list)
nx.draw_networkx(G = G_2)


python 复制代码
# 自定义可视化
edge_labels = nx.get_edge_attributes(G_2, "weight")
pos = nx.spring_layout(G_2) 
nx.draw_networkx_edge_labels(G_2, pos, edge_labels=edge_labels)  # 绘制图中边的权重
nx.draw_networkx(G_2, pos)


7. 读入、写出

write

  • 常用的有gexf、edgelist
  • 这部分比较简单,write、read
python 复制代码
# 1.gexf
nx.write_gexf(G,'./graph/G_01.gexf')
# 3. 保存为边列表
nx.write_edgelist(G, "./graph/G_01.edgelist")

read

python 复制代码
# 1. read_edgelist
G_read = nx.read_edgelist('./graph/G_01.edgelist')
nx.draw_networkx(G_read)


python 复制代码
# 1. read_gexf
G_read2 = nx.read_gexf('./graph/G_01.gexf')
nx.draw_networkx(G_read2)


相关推荐
泡海椒13 小时前
内置SPI函数库详解:JQuick-Java Builtin工具类实战用法
java·开发语言·python
hqyjzsb13 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
sanjiaomao33314 小时前
从论文公式到Python实现:用单元测试校验滑动平均算法
python·算法·单元测试
linweidong16 小时前
中科闻歌Java面试题及参考答案
java·python·大模型·提示词·ai agent·mcp·rag原理
小玮看世界16 小时前
[Python]OD算法在OD实际运用转化参考清单
开发语言·python·算法
萧鼎16 小时前
2026实战:用 tomlkit 优雅读写 TOML 配置,告别手写解析器
python·开源·教程·python库
小刘在重生~17 小时前
Java 常用类|包装类 装箱拆箱、Integer 缓存面试题
java·python·缓存
2601_9620994617 小时前
Python xlwt设置excel单元格字体及格式
python·excel·xlwt·样式设置·单元格格式
奇牙coding12318 小时前
GPT-6-Astra API 接入教程:OpenRouter 路由配置 + Python/curl 示例 + 静默降级踩坑
开发语言·python·gpt·ai
2601_9622982718 小时前
Python与Selenium结合的Web自动化测试全流程实践教程
自动化测试·python·selenium·web测试·pageobjectmodel