基于python的网络可视化工具代码
时间: 2023-09-27 22:11:57 浏览: 54
以下是基于Python的常用网络可视化工具代码:
1. Matplotlib + NetworkX
```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")
G.add_edge("A", "C")
G.add_edge("B", "D")
G.add_edge("C", "D")
# 绘制图形
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_color='lightblue', node_size=500)
nx.draw_networkx_edges(G, pos, edge_color='gray')
nx.draw_networkx_labels(G, pos, font_size=16, font_family='sans-serif')
# 显示图形
plt.axis('off')
plt.show()
```
2. Plotly
```python
# 导入所需的库
import plotly.graph_objs as go
import networkx as nx
# 创建一个无向图
G = nx.Graph()
# 添加节点
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")
# 添加边
G.add_edge("A", "B")
G.add_edge("A", "C")
G.add_edge("B", "D")
G.add_edge("C", "D")
# 绘制图形
pos = nx.spring_layout(G)
edge_trace = go.Scatter(x=[], y=[], line=dict(width=0.5, color='#888'))
for edge in G.edges():
x0, y0 = pos[edge[0]]
x1, y1 = pos[edge[1]]
edge_trace['x'] += tuple([x0, x1, None])
edge_trace['y'] += tuple([y0, y1, None])
node_trace = go.Scatter(x=[], y=[], text=[], mode='markers', hoverinfo='text', marker=dict(showscale=False, colorscale='YlGnBu', reversescale=True, color=[], size=20, colorbar=dict(thickness=15, xanchor='left', titleside='right')))
for node in G.nodes():
x, y = pos[node]
node_trace['x'] += tuple([x])
node_trace['y'] += tuple([y])
node_trace['text'] += tuple([node])
node_adjacencies = []
node_text = []
for node, adjacencies in enumerate(G.adjacency()):
node_adjacencies.append(len(adjacencies[1]))
node_text.append('# of connections: '+str(len(adjacencies[1])))
node_trace['marker']['color'] = node_adjacencies
node_trace['text'] = node_text
# 绘制图形
fig = go.Figure(data=[edge_trace, node_trace], layout=go.Layout(title='<br>Network graph made with Python', titlefont=dict(size=16), showlegend=False, hovermode='closest', margin=dict(b=20,l=5,r=5,t=40), xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)))
fig.show()
```
这些是常用的Python网络可视化工具,您可以根据自己的需求和数据来选择和调整网络图形。