我必须编写一段代码,从 MySQL 中获取一些数据并使用这些数据在 D3.js 中制作图表。当我以这种格式提供静态数据时,我的 D3.js 代码正在工作:
{
"name": " ",
"children": [{
"name": "HSC",
"size": 0.20,
"children": [
[{
"name": "MPP",
"size": 15,
"children": [{
"name": "CMP",
"size": 8,
"children": [{
"name": "MEP",
"size": 6
}, {
"name": "GMP",
"size": 10,
"children": [{
"name": "early PM",
"size": 2,
"children": [{
"name": "early PM",
"size": 2,
"children": []
}]
}]
}]
}]
}]
},
{
"name": "AML",
"size": 1,
"children": [{
"name": "AML t(8,21)",
"size": 30
}, {
"name": "AML t(11q23)",
"size": 10
}, {
"name": "AML inv(16)",
"size": 8
}, {
"name": "AML t(15,17)",
"size": 11
}]
}
], "size": 1
}
所以我需要一个用python编写的代码,它可以使用NetworkX制作像上面那样的JSON结构。
到目前为止我的代码:
n = 1 # the number of children for each node
depth = 1 # number of levels, starting from 0
G = nx.Graph()
G.add_node(1) # initialize root
ulim = 0
for level, row in enumerate(rows): #each row contains name and a size
print row # loop over each level
nl = n**level # number of nodes on a given level
llim = ulim + 1 # index of first node on a given level
ulim = ulim + nl # index of last node on a given level
for i in range(nl): # loop over nodes (parents) on a given level
parent = llim + i
offset = ulim + i * n + 1 # index pointing to node just before first child
for j in range(n): # loop over children for a given node (parent)
child = offset + j
G.add_node(child)
G.add_edge(parent, child)