2
我有以下代码:如何使Networkx产生GML文件,排序节点
#!/usr/bin/env python
import networkx as nx
def main():
"""docstring for main"""
outerdict = {"A":["a1","a2","a3"], "B":["b1","b2","b3","b5","b6", "b7"], "C":["c2","c3"], "D":["d1","d2","d3"]}
keynode = "Z"
colorlist = [ "#beaed4", "#fdc086", "#ffff99", "#386cb0","#f0027f"]
G = nx.Graph()
G.add_node(keynode,graphics={"fill":"#7fc97f","w":27,"h":27, "d":27})
for i,ky in enumerate(outerdict):
nodes = outerdict[ky]
nodecol = colorlist[i]
print ky, nodecol
for node in nodes:
G.add_node(node,graphics={"fill":nodecol,"w":27,"h":27,"d":27})
G.add_edge(keynode, node, value = 10)
outfile = "test.gml"
nx.write_gml(G,outfile)
if __name__ == '__main__':
main()
它生成以下文件GML:
graph [
node [
id 0
label "b6"
graphics [
h 27
d 27
w 27
fill "#ffff99"
]
]
node [
id 1
label "a1"
graphics [
h 27
d 27
w 27
fill "#beaed4"
]
]
node [
id 2
label "b5"
graphics [
h 27
d 27
w 27
fill "#ffff99"
]
]
node [
id 3
label "a3"
graphics [
h 27
d 27
w 27
fill "#beaed4"
]
]
node [
id 4
label "a2"
graphics [
h 27
d 27
w 27
fill "#beaed4"
]
]
node [
id 5
label "b7"
graphics [
h 27
d 27
w 27
fill "#ffff99"
]
]
node [
id 6
label "b1"
graphics [
h 27
d 27
w 27
fill "#ffff99"
]
]
node [
id 7
label "b2"
graphics [
h 27
d 27
w 27
fill "#ffff99"
]
]
node [
id 8
label "b3"
graphics [
h 27
d 27
w 27
fill "#ffff99"
]
]
node [
id 9
label "c3"
graphics [
h 27
d 27
w 27
fill "#fdc086"
]
]
node [
id 10
label "c2"
graphics [
h 27
d 27
w 27
fill "#fdc086"
]
]
node [
id 11
label "Z"
graphics [
h 27
d 27
w 27
fill "#7fc97f"
]
]
node [
id 12
label "d2"
graphics [
h 27
d 27
w 27
fill "#386cb0"
]
]
node [
id 13
label "d3"
graphics [
h 27
d 27
w 27
fill "#386cb0"
]
]
node [
id 14
label "d1"
graphics [
h 27
d 27
w 27
fill "#386cb0"
]
]
edge [
source 0
target 11
value 10
]
edge [
source 1
target 11
value 10
]
edge [
source 2
target 11
value 10
]
edge [
source 3
target 11
value 10
]
edge [
source 4
target 11
value 10
]
edge [
source 5
target 11
value 10
]
edge [
source 6
target 11
value 10
]
edge [
source 7
target 11
value 10
]
edge [
source 8
target 11
value 10
]
edge [
source 9
target 11
value 10
]
edge [
source 10
target 11
value 10
]
edge [
source 11
target 12
value 10
]
edge [
source 11
target 13
value 10
]
edge [
source 11
target 14
value 10
]
]
注意,节点不按顺序排列。例如a1
介于b1
和b5
之间。这使得情节是这样的:
我希望图什么是根据环路和初始数据结构outderdict
依次顺序。因此,黄色节点将与其他黄色等顺序连在一起。
如何使用Networkx对GML文件进行排序?其他解决方案(例如Igraph)只要在Python框架内受欢迎。
你不能使用ordereddict吗?按键顺序将随机使用标准字典,否则在添加节点之前,您必须首先对字典中的值进行排序。 – EdChum 2015-03-13 09:27:15
@EdChum:每种颜色(黄色,蓝色,紫色等)对应一个键。它不必订购。我们想要的是每个键的**成员**应该一起排列,例如,所有黄色节点不应该与紫色节点交替。由于成员包含在**列表**中,因此应该默认按顺序排列。但创建GML时'networkx'不知道顺序。 – pdubois 2015-03-13 13:13:17