我面临与SO问题here类似的问题,与所描述的数据几乎相同:
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}
但是,如果我将此图形数据提供给链接脚本,它会将数据键与值(例如“1”(第一行的键)连接为“2”(第二行的键)连接数据集中的下一行)
清除它,举一个例子:我想将第一行的“1”连接到第一行的2,3,4,而不是连接第二行的2。此外,我希望将所有值相互连接,例如2与3,其中4与5与11,依此类推。
这无论如何都清楚了吗?
应保留链接脚本的所有剩余功能(例如通过数字边缘,节点标签等调整节点的圆形大小)。
修改
感谢Wayne Werner,我发现我的解释中有一个错误:考虑以下数据集的以下数据:
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
在这种情况下,我想连接3与6,7,66,77但不与3连接5 此外,我想连接5与6,8,66,77。
答案 0 :(得分:1)
What you're asking is possible, I think you're just confused about how NetworkX graphs work. When you add a node to the graph, you pass in an ID to represent that node. Internally NetworkX uses this value to track individual nodes. When connect two nodes together, you pass two ids (representing nodes) to connect.
In your explanation of your problem you are wanting NetworkX to accept the same ID twice, but 'forget' that ID already represents a node. That's not possible.
You have two options:
The following is an example of the second approach. Here the key in the graph
dictionary is used to create a unique ID set for each subgraph, e.g. 1_2
, 1_3
, 1_4
, etc. We store the unique IDs with the label, and apply these when creating the plot. That way it looks like multiple nodes have the same ID, even though they do not.
import networkx
from itertools import combinations
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}
g = networkx.Graph()
labels = {}
for k, vs in graph.items():
vs.append(k)
for a, b in combinations(vs, 2):
# We're creating multiple 'subnetworks', so prefix the ids
node_a = '%s_%s' % (k, a)
node_b = '%s_%s' % (k, b)
g.add_edge(node_a,node_b)
# Store labels
labels[node_a] = a
labels[node_b] = b
# Draw the graph, replacing the labels to hide the unique IDs
networkx.draw_spring(g, labels=labels)
This produces the following image, as you can see multiple nodes have the same label, even though behind the scenes they have distinct IDs.