Question

I create representation of graph with NetworkX library in my python project. Making directed graph I need to add an attribute to our graph output: rankdir=LR

So I'm writing the code:

import networkx as nx
graph = nx.DiGraph(rankdir="LR")
#adding deps based on our database data
add_deps(graph)
dot_file_path = "some/path/to/dots.gv"

nx.write_dot(graph, dot_file_path)

So, last string generates dot file with next content:

strict digraph  {
    "Writing letters"    [URL="/admin/materials/theme/213/",
        shape=box,
        target=blank];
    "Finishing the Business English course"  [URL="/admin/materials/theme/221/",
        color=red,
        shape=box,
        style=filled,
        target=blank];
    "Writing letters" -> "Finishing the Business English course";
    ... 
}

While I expect the code where attribute "rankdir=LR" will be attached to the graph output:

strict digraph  {
    rankdir=LR;
    "Writing letters"    [URL="/admin/materials/theme/213/",
        shape=box,
        target=blank];
    "Finishing the Business English course"  [URL="/admin/materials/theme/221/",
        color=red,
        shape=box,
        style=filled,
        target=blank];
    "Writing letters" -> "Finishing the Business English course";
    ... 
}

But this doesn't happen, seems that write_dot() method doesn't put graph atrributes. Could anyone help me with advice of the correct way of adding graph attributes through networkx?

Was it helpful?

Solution

It's not very well documented. You can add default "graph" properties like this:

In [1]: import networkx as nx

In [2]: G = nx.DiGraph()

In [3]: G.add_edge(1,2)

In [4]: G.graph['graph']={'rankdir':'LR'}

In [5]: import sys

In [6]: nx.write_dot(G, sys.stdout)
strict digraph  {
    graph [rankdir=LR];
    1 -> 2;
}

OTHER TIPS

AGraph

This is an addendum to Aric's helpful answer. AGraphs don't have the graph attribute, but graph_attr without the additional 'graph' key works:

A.graph_attr['rankdir'] = 'LR'

DiGraph

Also, since your DiGraph might already have a .graph['graph'] key with some attributes, you may want to use setdefault instead of assigning a new dict directly:

G.graph.setdefault('graph', {})['rankdir'] = 'LR'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top