提供一段python代码:将一个无向带权符号网络可视化,点、边和权重的信息由excel表读入,将正边和负边用颜色区分开,边的粗细等于权重大小
时间: 2023-06-05 20:04:06 浏览: 165
以下是实现该要求的Python代码片段,需要安装networkx和matplotlib库:
```python
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
# 读取excel表格中的点、边和权重数据
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
nodes = df['node'].tolist()
edges = [(u, v, w) for u, v, w in zip(df['from'], df['to'], df['weight'])]
# 创建无向带权图
G = nx.MultiGraph()
G.add_nodes_from(nodes)
for u, v, w in edges:
G.add_edge(u, v, weight=w)
# 绘制图像
positive_edges = [(u, v) for u, v, w in edges if w > 0]
negative_edges = [(u, v) for u, v, w in edges if w < 0]
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size=500, node_color='pink')
nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif')
nx.draw_networkx_edges(G, pos, edgelist=positive_edges, width=[abs(w) for u, v, w in edges if w > 0], edge_color='green')
nx.draw_networkx_edges(G, pos, edgelist=negative_edges, width=[abs(w) for u, v, w in edges if w < 0], edge_color='red')
nx.draw_networkx_edge_labels(G, pos, edge_labels={(u, v):w for u, v, w in edges}, font_size=10)
plt.axis('off')
plt.show()
```
其中,'data.xlsx'为存储包含点、边和权重信息的Excel文件名,Sheet1为Excel表格的表格名。代码运行后,将会生成一个带权无向图,并用颜色区分正边和负边,边的粗细等于权重大小。
阅读全文