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
有权无向图

posted @ 2018-06-20 11:15  好奇不止,探索不息  阅读(6252)  评论(1编辑  收藏  举报