import pandas as pd import numpy as np 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=(15,15)) G = nx.DiGraph() for edge in edges: G.add_edge(edge["tail"], edge["head"], weight=edge["length"]) 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.5) plt.show() all_pairs = dict(nx.all_pairs_dijkstra_path_length(G)) rows = [] for start_node, dist_dict in all_pairs.items(): for end_node, dist in dist_dict.items(): rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': dist}) df_result = pd.DataFrame(rows) df_result.to_excel('all_pairs.xlsx', index=False)在上述代码的基础上,计算每一顶点到其它各顶点之间最短路长度的平均值,采用合适的图表形式予以表达,并讨论该结果反映了网络中哪些信息
时间: 2024-02-28 18:55:28 浏览: 132
python数据分析与可视化 import pandas as pd import numpy as np import m
可以通过以下代码来计算每一顶点到其它各顶点之间最短路长度的平均值,并用柱状图来表达:
```python
import pandas as pd
import numpy as np
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=(15,15))
G = nx.DiGraph()
for edge in edges:
G.add_edge(edge["tail"], edge["head"], weight=edge["length"])
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.5)
plt.show()
all_pairs = dict(nx.all_pairs_dijkstra_path_length(G))
rows = []
for start_node, dist_dict in all_pairs.items():
for end_node, dist in dist_dict.items():
rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': dist})
df_result = pd.DataFrame(rows)
df_result.to_excel('all_pairs.xlsx', index=False)
# 计算每个节点到其他节点的平均最短距离
avg_dists = []
for node in G.nodes():
dist_sum = 0
for dist in all_pairs[node].values():
dist_sum += dist
avg_dist = dist_sum / len(G.nodes())
avg_dists.append(avg_dist)
# 画柱状图
plt.bar(G.nodes(), avg_dists)
plt.title("每个节点到其他节点的平均最短距离")
plt.xlabel("节点")
plt.ylabel("平均最短距离")
plt.show()
```
该结果反映了网络中各个节点之间的连接距离的平均水平,能够帮助我们了解网络的整体结构和性质,以及节点间的相互关系是否紧密。同时,如果网络中存在一些节点的平均最短距离较大,这可能表示这些节点在整个网络中的重要性较低,可以考虑进行优化或改进。
阅读全文