python构建图与笔记

时间:2012-04-22 08:20:32

标签: python graph networkx

我想构建有向图并订阅边缘。

import os
import scipy as sc
import pylab
import networkx 
import matplotlib.pyplot as plt
from networkx import *
from numpy import *

G=networkx.DiGraph()
R=[('S0','S1'),('S1','S2'),('S1','S7'),('S2','S3'),('S2','S6'),('S3','S4'),('S3','S6'),('S4','S5'),('S5','S6'),('S6','S7'),('S7','S8'),('S7','S5'),('S8','Sk') ] 

G.add_edges_from([ (2,3,) ])
G.add_edges_from(R) 
networkx.draw_circular(G)

plt.show()
plt.savefig("path.png");

现在我已经这样做了。我构建了一个图表,但我想不出如何订阅边缘。例如,我想标记S0S1边缘,如"565"等。这将使其更具视觉效果和演示效果。 提前谢谢!

enter image description here

3 个答案:

答案 0 :(得分:3)

您可以单独布局和绘制节点,边,节点标签和边标签,而不是在一个步骤(networkx.draw_circular(G))中进行布局和绘图。这是一个小例子:

import networkx as nx
import matplotlib.pyplot as plt

G=nx.DiGraph()
R=[('S0','S1'),('S1','S2'),('S1','S7'),('S0','S7')] 

G.add_edges_from(R)

# Calculate layout and get all positions
pos = nx.circular_layout(G)

# Draw everything
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(G, pos, 
    {
        ('S0', 'S1'): 'edge1',
        ('S1', 'S2'): 'edge2',
        ('S1', 'S7'): 'edge3',
        ('S0', 'S7'): 'edge4'
    }
)

plt.axis('off')
plt.savefig("path.png");
plt.show()

有关可以将哪些参数传递给不同绘图函数的更多信息,check the documentation

答案 1 :(得分:1)

您可以选择性地绘制节点和边:

# nodes
networkx.draw_networkx_nodes(graph, pos, nodelist=[list of the nodes])
# edges
networkx.draw_networkx_edges(graph, pos, edgelist=[list of edges])

http://networkx.lanl.gov/reference/drawing.html#module-networkx.drawing.nx_pylab

还有更多选项

答案 2 :(得分:1)

好吧,我想这样做:enter image description here 我做到了即我想标记边缘。这似乎很简单,但事实并非如此。真。

完整图片在这里http://s019.radikal.ru/i603/1204/2a/921bc6badfae.png

 import os
 import scipy as sc
 import pylab
 import networkx 
 import matplotlib.pyplot as plt
 from networkx import *
 from numpy import *

 G=networkx.DiGraph()
 R=[('S0','S1'),('S1','S2'),('S1','S7'),('S2','S3'),('S2','S6'),('S3','S4'),('S3','S6'),('S4','S5'),('S5','S6'),('S6','S7'),('S7','S8'),('S7','S5'),('S8','Sk') ] 
 G.add_edges_from(R) 
 label={R[1]:'a',R[2]:'b',R[3]:'c'}
 networkx.draw_networkx_edge_labels(G,pos=networkx.graphviz_layout(G),edge_labels=label)
 networkx.draw_graphviz(G)
 plt.show()
 plt.savefig("path.png");