Reputation:
I have a dot file representing a Directed Graph (DiGraph
). I want that to be read in a networkx DiGraph object.
I used the networkx.drawing.nx_agraph.read_dot(PATH)
, however the nodes in the graph this function returns are just simple 'str'
types and the labels are all lost in translation.
Dotfile is like this:
digraph code {
graph [bgcolor=white fontname="Courier" splines="ortho"];
node [fillcolor=gray style=filled shape=box];
edge [arrowhead="normal"];
"0x000052c0" -> "0x00003a40" [label="section..text" color="red" URL="section..text/0x00003a40"];
"0x00003a40" [label="section..text" URL="section..text/0x00003a40"];
"0x000052c0" -> "0x0021ee08" [label="reloc.__libc_start_main_8" color="green" URL="reloc.__libc_start_main_8/0x0021ee08"];
"0x0021ee08" [label="reloc.__libc_start_main_8" URL="reloc.__libc_start_main_8/0x0021ee08"];
}
What I wrote to read this file is this:
import networkx as nx
G = nx.drawing.nx_agraph.read_dot(DOT_GRAPH_NAME)
Does anyone have a better method? I could write my own but it's better to have something working and tested.
Upvotes: 1
Views: 2135
Reputation: 21
From the source code file networkx/drawing/nx_agraph.py, the follow code can be found:
# add nodes, attributes to N.node_attr
for n in A.nodes():
str_attr = {str(k): v for k, v in n.attr.items()}
N.add_node(str(n), **str_attr)
...
N.graph['node'] = dict(A.node_attr)
So, the node attributes are also parsed. You can find this field by
vars(g)
In my case, I can get the label by
for node_id in g.nodes:
print g._node[node_id]['label'] # here, 'node_id' is the 'str' you said
Upvotes: 2