import pandas as pd import networkx as nx import matplotlib.pyplot as plt df = pd.read_excel(r"C:\Users\li'yi'jie\Desktop\运筹学网络规划数据.xlsx") edges = [] for i in range(len(df)): edge = { "id": df.loc[i, "边的编号"], "tail": df.loc[i, "边的尾节点"], "head": df.loc[i, "边的头节点"], "length": df.loc[i, "长度"], "capacity": df.loc[i, "容量"] } edges.append(edge) plt.figure(figsize=(10,8)) G = nx.DiGraph() for edge in edges: G.add_edge(edge["tail"], edge["head"], weight=edge["length"]) all_pairs = dict(nx.all_pairs_dijkstra_path_length(G)) pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True) labels = nx.get_edge_attributes(G, "weight") nx.draw_networkx_edge_labels(G, pos, edge_labels=labels) plt.show()如何修改能使权重写在边旁而非边上?
时间: 2024-01-02 13:03:26 浏览: 65
要将边权重标签写在边旁,可以使用 `nx.draw_networkx_edge_labels()` 函数的 `label_pos` 参数来指定标签的位置。将 `label_pos` 设置为 0.5 将标签放置在边的中心位置,将其设置为 0.3 或 0.7 将标签放置在边的侧面。修改后的代码如下所示:
```
import pandas as pd import networkx as nx import matplotlib.pyplot as plt df = pd.read_excel(r"C:\Users\li'yi'jie\Desktop\运筹学网络规划数据.xlsx") edges = [] for i in range(len(df)): edge = { "id": df.loc[i, "边的编号"], "tail": df.loc[i, "边的尾节点"], "head": df.loc[i, "边的头节点"], "length": df.loc[i, "长度"], "capacity": df.loc[i, "容量"] } edges.append(edge) plt.figure(figsize=(10,8)) G = nx.DiGraph() for edge in edges: G.add_edge(edge["tail"], edge["head"], weight=edge["length"]) all_pairs = dict(nx.all_pairs_dijkstra_path_length(G)) pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True) labels = nx.get_edge_attributes(G, "weight") nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.3) plt.show()
```
运行后即可在图形中看到边权重标签被放置在了边的侧面。
阅读全文