How to add dot's graph attribute into final dot output
Asked Answered
A

2

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?

Admissible answered 2/1, 2014 at 15:19 Comment(0)
B
20

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;
}
Barbecue answered 2/1, 2014 at 20:5 Comment(1)
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.Cakewalk
A
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'
Alar answered 28/3, 2014 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.