修改代码,将图形绘制成一个矩形布局:import matplotlib.pyplot as plt# 将图形绘制成一个圆形布局pos = nx.circular_layout(G)# 绘制图形的节点和边nx.draw_networkx_nodes(G, pos)nx.draw_networkx_edges(G, pos)# 添加节点标签node_labels = {node: str(node) for node in G.nodes()}nx.draw_networkx_labels(G, pos, node_labels)# 添加边权重标签edge_labels = {(u, v): str(d['weight']) for u, v, d in G.edges(data=True)}nx.draw_networkx_edge_labels(G, pos, edge_labels)# 显示图形plt.show()
时间: 2024-03-04 08:49:05 浏览: 157
import numpy as np import matplotlib.pyplot as plt import math
在这个示例代码中,我们可以使用 `nx.spring_layout()` 方法来生成矩形布局。以下是修改后的代码:
```python
import matplotlib.pyplot as plt
import networkx as nx
# 创建一个图形对象
G = nx.Graph()
# 添加节点和边
G.add_edges_from([(1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (4, 5), (5, 6)])
# 生成矩形布局
pos = nx.spring_layout(G, k=0.5, iterations=50)
# 绘制图形的节点和边
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
# 添加节点标签
node_labels = {node: str(node) for node in G.nodes()}
nx.draw_networkx_labels(G, pos, node_labels)
# 添加边权重标签
edge_labels = {(u, v): str(d['weight']) for u, v, d in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels)
# 显示图形
plt.show()
```
在这个修改后的代码中,我们只需要将 `pos` 变量的赋值改为 `nx.spring_layout(G, k=0.5, iterations=50)` 就可以生成矩形布局了。
阅读全文