1.创建图
创建一个没有结点也没有边的空图
结点可以是任意hash对象,字符串、图像、
import networkx as nx
G = nx.Graph()
2.添加图的结点
def test_node(self):
G = nx.Graph()
#add_node()添加一个结点
G.add_node(1)
print(G.nodes)
#add_nodes_from()添加多个结点
G.add_nodes_from([2, 3])
print(G.nodes)
G.add_nodes_from([
(4, {
"color": "red"}),
(5, {
"color": "green"}),
])
print(G.nodes)
print(G.nodes.data())
#将一个图中的结点合并到另一个图中
H = nx.path_graph(10)
G.add_nodes_from(H)
print(G.nodes)
print(G.nodes.data())
输出结果
[1]
[1, 2, 3]
[1, 2, 3, 4, 5]
[(1, {
}), (2, {
}), (3, {
}), (4, {
'color': 'red'}), (5, {
'color': 'green'})]
[1, 2, 3, 4, 5, 0, 6, 7, 8, 9]
[(1, {
}), (2, {
}), (3, {
}), (4, {
'color': 'red'}), (5, {
'color': 'green'}), (0, {
}), (6, {
}), (7, {
}), (8, {
}), (9, {
})]
[1, 2, 3, 4, 5, 0, 6, 7, 8, 9, <networkx.classes.graph.Graph object at 0x0000028B528B66A0>]
[(1, {
}), (2, {
}), (3, {
}), (4, {
'color': 'red'}), (5, {
'color': 'green'}), (0, {
}), (6, {
}), (7, {
}), (8, {
}), (9, {
}), (<networkx.classes.graph.Graph object at 0x0000028B528B66A0>, {
})]
3.添加图的边
def test_edge(self):
G = nx.Graph()
#add_edge()添加一条边
G.add_edge(1, 2)
e = (2, 3)
G.add_edge(*e)
print(G.edges)
print(G.edges.data())
#添加边列表
G.add_edges_from([(1, 2), (1, 3)])
print(G.edges)
print(G.edges.data())
H = nx.path_graph(10)
print(H.edges)
G.add_edges_from(H.edges