5005.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import networkx as nx
  2. import plotly.graph_objects as go
  3. # 创建一个空的Graph
  4. G = nx.DiGraph()
  5. # 添加节点和边
  6. G.add_edge('A', 'B', weight=1)
  7. G.add_edge('A', 'C', weight=2)
  8. G.add_edge('B', 'C', weight=3)
  9. G.add_edge('C', 'D', weight=4)
  10. # 使用spring布局获取节点位置
  11. pos = nx.spring_layout(G)
  12. # 创建一个节点列表和边列表,用于绘图
  13. edge_x = []
  14. edge_y = []
  15. for edge in G.edges():
  16. x0, y0 = pos[edge[0]]
  17. x1, y1 = pos[edge[1]]
  18. edge_x.append(x0)
  19. edge_x.append(x1)
  20. edge_x.append(None) # None 表示断开,用于绘制多条线段
  21. edge_y.append(y0)
  22. edge_y.append(y1)
  23. edge_y.append(None)
  24. # 创建节点数据
  25. node_x = [pos[node][0] for node in G.nodes()]
  26. node_y = [pos[node][1] for node in G.nodes()]
  27. # 创建节点和边轨迹
  28. edge_trace = go.Scatter(
  29. x=edge_x, y=edge_y,
  30. line=dict(width=0.5, color='black'),
  31. hoverinfo='none',
  32. mode='lines')
  33. node_trace = go.Scatter(
  34. x=node_x, y=node_y,
  35. text=[],
  36. mode='markers',
  37. hoverinfo='text',
  38. marker=dict(
  39. showscale=True,
  40. # colorscale options
  41. #'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' |
  42. #'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' |
  43. #'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' |
  44. colorscale='YlGnBu',
  45. reversescale=True,
  46. color=[],
  47. size=10,
  48. colorbar=dict(
  49. thickness=15,
  50. title='Node Connections',
  51. xanchor='left',
  52. titleside='right'
  53. ),
  54. line_width=2))
  55. # 更新节点颜色和大小
  56. node_adjacencies = []
  57. node_text = []
  58. for node, adjacencies in enumerate(G.adjacency()):
  59. node_adjacencies.append(len(adjacencies[1]))
  60. node_text.append('# of connections: '+str(len(adjacencies[1])))
  61. node_trace.marker.color = node_adjacencies
  62. node_trace.text = node_text
  63. # 创建图布局
  64. fig = go.Figure(data=[edge_trace, node_trace],
  65. layout=go.Layout(
  66. title='Interactive Network Graph',
  67. titlefont_size=16,
  68. showlegend=False,
  69. hovermode='closest',
  70. margin=dict(b=20,l=5,r=5,t=40),
  71. annotations=[ dict(
  72. text="Python code: <a href='https://plotly.com/'> Plotly</a>",
  73. showarrow=False,
  74. xref="paper", yref="paper",
  75. x=0.005, y=-0.002 ) ],
  76. xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
  77. yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
  78. )
  79. # 显示图形
  80. fig.show()