12

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?

2 Answers 2

22

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

For those who use new versions (>=2.0) of NetworkX, use drawing.nx_pydot.write_dot or drawing.nx_agraph.write_dot instead of write_dot.
4

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.