我试图生成一个可视化数据沿袭的网络图(集群图,如this)。请记住,我对NetworkX库非常陌生,下面的代码可能远不是最佳的。在
我的数据由两个Pandas数据帧组成:
df_objs
:这个df包含一个UUID和不同项的名称(这些项将成为节点)df_calls
:这个df包含一个调用和被调用的UUID(这些UUID是对df_objs
中项目的UUID的引用)。在下面是初始化有向图并创建节点的步骤:
import networkx as nx
objs = df_objs.set_index('uuid').to_dict(orient='index')
g = nx.DiGraph()
for obj_id, obj_attrs in objs.items():
g.add_node(obj_id, attr_dict=obj_attrs)
要生成边:
^{pr2}$接下来,我想知道使用UUID的单个项目的沿袭:
g_tree = nx.DiGraph(nx.bfs_edges(g, 'f6e214b1bba34a01bd0c18f232d6aee2', reverse=True))
到目前为止还不错。最后一步是生成JSON图,以便将生成的JSON文件馈送到D3.js,以便执行可视化:
# Create the JSON data structure
from networkx.readwrite import json_graph
data = json_graph.tree_data(g_tree, root='f6e214b1bba34a01bd0c18f232d6aee2')
# Write the tree to a JSON file
import json
with open('./tree.json', 'w') as f:
json.dump(data, f)
但是,上面所有的工作都是这样,而不是节点名,而是JSON数据中的UUID,因为在调用nx.bfs_edges()
时节点属性被删除了。在
示例:
没问题(至少我是这么想的);我将用g
中的属性更新g_tree
中的节点。在
obj_names = nx.get_node_attributes(g, 'name')
for obj_id, obj_name in obj_names.items():
try:
g_tree[obj_id]['name'] = obj_name
except Exception:
pass
注意:我不能使用set_node_attributes()
,因为g
包含的节点多于g_tree
,这会导致KeyError
。在
如果我再次尝试生成JSON数据:
data = json_graph.tree_data(g_tree, root='f6e214b1bba34a01bd0c18f232d6aee2')
它将抛出错误:
TypeError: G is not a tree.
这是由于number of nodes != number of edges + 1
。在
在设置属性之前,节点数为81,边数为80。设置属性后,边数增加到120(节点数保持不变)。在
好吧,关于我的问题:
根据关于dict
G[node]
的warning in the docs因此,对
g_tree[obj_id]
的赋值是否定的:而是使用^{} 修改属性:
^{pr2}$另外,一旦有了
g_tree
,就可以使用然后你可以用
将属性从
g
复制到g_tree
。在相关问题 更多 >
编程相关推荐