1

我想使用 d3js 来可视化我的 Django 网站用户之间的联系。我正在重用强制有向图示例的代码,它要求每个节点都有两个属性(ID 和名称)。我在 user_profiles_table 中为每个用户创建了一个节点,并根据 connections_table 中的每一行在已创建的节点之间添加了一条边。这没用; 当我开始使用 connection_table 时,networkx 会创建新节点。

nodeindex=0
for user_profile in UserProfile.objects.all():
    sourcetostring=user_profile.full_name3()
    G.add_node(nodeindex, name=sourcetostring)
    nodeindex = nodeindex +1

for user_connection in Connection.objects.all():
    target_tostring=user_connection.target()
    source_tostring=user_connection.source()
    G.add_edge(sourcetostring, target_tostring, value=1)

data = json_graph.node_link_data(G)

结果:

 {'directed': False,
 'graph': [],
 'links': [{'source': 6, 'target': 7, 'value': 1},
  {'source': 7, 'target': 8, 'value': 1},
  {'source': 7, 'target': 9, 'value': 1},
  {'source': 7, 'target': 10, 'value': 1},
  {'source': 7, 'target': 7, 'value': 1}],
 'multigraph': False,
 'nodes': [{'id': 0, 'name': u'raymondkalonji'},
  {'id': 1, 'name': u'raykaeng'},
  {'id': 2, 'name': u'raymondkalonji2'},
  {'id': 3, 'name': u'tester1cet'},
  {'id': 4, 'name': u'tester2cet'},
  {'id': 5, 'name': u'tester3cet'},
  {'id': u'tester2cet'},
  {'id': u'tester3cet'},
  {'id': u'tester1cet'},
  {'id': u'raykaeng'},
  {'id': u'raymondkalonji2'}]}

如何消除重复节点?

4

1 回答 1

4

您可能会得到重复的节点,因为您的user_connection.target()anduser_connection.source()函数返回的是节点名称,而不是它的 ID。当您调用 时add_edge,如果图中不存在端点,则会创建它们,这解释了为什么会出现重复。

以下代码应该可以工作。

for user_profile in UserProfile.objects.all():
    source = user_profile.full_name3()
    G.add_node(source, name=source)

for user_connection in Connection.objects.all():
    target = user_connection.target()
    source = user_connection.source()
    G.add_edge(source, target, value=1)

data = json_graph.node_link_data(G)

另请注意,data如果您想要格式正确的 json 字符串,则应将对象转储到 json。您可以按如下方式进行。

import json
json.dumps(data)                  # get the string representation
json.dump(data, 'somefile.json')  # write to file
于 2013-07-07T21:22:17.123 回答