import networkx as nx import matplotlib.pyplot as plt # create graph object G = nx.Graph() # add nodes G.add_node('A') G.add_node('B') G.add_node('C') G.add_node('D') # add edges with weights G.add_edge('A', 'B', weight=5) G.add_edge('A', 'C', weight=7) G.add_edge('B', 'D', weight=6) G.add_edge('C', 'D', weight=3) # define node positions (optional) pos = {'A': (0, 0), 'B': (1, 1), 'C': (-1, 1), 'D': (0, 2)} # draw nodes and edges with labels nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos) edge_labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) plt.axis('off') plt.show()
时间: 2023-08-22 16:07:16 浏览: 240
这段代码也可以用来绘制带权图,它和我之前给出的示例代码有些不同。以下是这段代码的解释:
```python
import networkx as nx
import matplotlib.pyplot as plt
# 创建一个带权图
G = nx.Graph()
# 添加节点
G.add_node('A')
G.add_node('B')
G.add_node('C')
G.add_node('D')
# 添加带权边
G.add_edge('A', 'B', weight=5)
G.add_edge('A', 'C', weight=7)
G.add_edge('B', 'D', weight=6)
G.add_edge('C', 'D', weight=3)
# 定义节点位置
pos = {'A': (0, 0), 'B': (1, 1), 'C': (-1, 1), 'D': (0, 2)}
# 绘制节点和边以及标签
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
# 获取边的权重并绘制标签
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.axis('off')
plt.show()
```
在这个示例中,我们首先创建了一个带权图,然后添加了节点和带权边。接下来,我们定义了节点位置,这是可选的,如果不定义位置,则networkx会自动为节点排列位置。然后我们使用`nx.draw_networkx_nodes`、`nx.draw_networkx_edges`和`nx.draw_networkx_labels`这三个函数来绘制节点和边,并使用`nx.get_edge_attributes`获取边的权重。最后,我们使用`nx.draw_networkx_edge_labels`函数来绘制边的标签。
阅读全文