NetworkX系列教程(4)-設置graph的信息


要畫出美觀的graph,需要對graph里面的節點,,節點的布局都要進行設置,具體可以看官方文檔:Adding attributes to graphs, nodes, and edges部分.

目錄:


注意:如果代碼出現找不庫,請返回第一個教程,把庫文件導入.

5.設置graph的信息

5.1創建graph時添加屬性

  1. #G.clear() 
  2. G=nx.Graph() 
  3. G = nx.Graph(day="Friday") 
  4. print('Assign graph attributes when creating a new graph: ',G.graph) 
  5. G.graph['day'] = "Monday" 
  6. print('Assign graph attributes when have a graph: ',G.graph) 

輸出:

Assign graph attributes when creating a new graph: {'day': 'Friday'}
Assign graph attributes when have a graph: {'day': 'Monday'}

5.2指定節點的屬性

  1. #創建時設置 
  2. G.add_node(1, time='5pm') 
  3. G.add_nodes_from([3,4], time='2pm',color='g') 
  4.  
  5. #直接設置 
  6. G.nodes[1]['room'] = 714 
  7. G.nodes[1]['color'] = 'b' 
  8.  
  9. print(G.nodes.data()) 

輸出:

[(1, {'room': 714, 'time': '5pm', 'color': 'b'}), (3, {'time': '2pm', 'color': 'g'}), (4, {'time': '2pm', 'color': 'g'})]

5.3指定邊的屬性

  1. #創建時設置 
  2. G.add_edge(1, 2, weight=4.7 ) 
  3. G.add_edges_from([(3, 4), (4, 5)], color='red',weight=10) 
  4. G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})]) 
  5.  
  6. #直接設置 
  7. G[1][2]['weight'] = 4.7 
  8. G[1][2]['color'] = "blue" 
  9. G.edges[3, 4]['weight'] = 4.2 
  10. G.edges[1, 2]['color'] = "green" 
  11.  
  12. print('edge 1-2: ',G.edges[1,2]) 
  13. print('edge 3-4: ',G.edges[3,4]) 

輸出:

edge 1-2: {'weight': 4.7, 'color': 'green'}
edge 3-4: {'weight': 4.2, 'color': 'red'}

5.4顯示graph

  1. #生成節點標簽 
  2. labels={} 
  3. labels[1]='1' 
  4. labels[2]='2' 
  5. labels[3]='3' 
  6. labels[4]='4' 
  7. labels[5]='5' 
  8.  
  9. #獲取graph中的邊權重 
  10. edge_labels = nx.get_edge_attributes(G,'weight') 
  11. print('weight of all edges:',edge_labels) 
  12.  
  13. #生成節點位置 
  14. pos=nx.circular_layout(G) 
  15. print('position of all nodes:',pos) 
  16.  
  17. #把節點畫出來 
  18. nx.draw_networkx_nodes(G,pos,node_color='g',node_size=500,alpha=0.8) 
  19.  
  20. #把邊畫出來 
  21. nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5,edge_color='b') 
  22.  
  23. #把節點的標簽畫出來 
  24. nx.draw_networkx_labels(G,pos,labels,font_size=16) 
  25.  
  26. #把邊權重畫出來 
  27. nx.draw_networkx_edge_labels(G, pos, edge_labels) 
  28.  
  29. plt.axis('on') 
  30. #去掉坐標刻度 
  31. plt.xticks([]) 
  32. plt.yticks([]) 
  33. plt.show() 

輸出:

weight of all edges: {(1, 2): 4.7, (3, 4): 4.2, (2, 3): 8, (4, 5): 10}
position of all nodes: {1: array([1.00000000e+00, 2.38418583e-08]), 2: array([0.30901696, 0.95105658]), 3: array([-0.80901709, 0.58778522]), 4: array([-0.80901698, -0.58778535]), 5: array([ 0.30901711, -0.95105647])}

enter description here
有權無向圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM