How can python write a dot file for GraphViz askin

2019-05-22 21:05发布

问题:

I am using python code (with python nested dicts) to write out a DOT file for GraphViz to draw my directed edge-weighted graph, thanks to DAWG's suggestions...

nestedg={1: {2: 3, 3: 8, 5: -4}, 
     2: {4: 1, 5: 7}, 
     3: {2: 0.09}, 
     4: {1: 2, 3: -5}, 
     5: {4: 6}}

with open('/tmp/graph.dot','w') as out:
    for line in ('digraph G {','size="16,16";','splines=true;'):
        out.write('{}\n'.format(line))  
    for start,d in nestedg.items():
        for end,weight in d.items():
              out.write('{} -> {} [ label="{}" ];\n'.format(start,end,weight))
    out.write('}\n')

Which produces this .DOT file, from which GraphViz can produce a nice graph image:

digraph G {
size="16,16";
splines=true;
1 -> 2 [ label="3" ];
1 -> 3 [ label="8" ];
1 -> 5 [ label="-4" ];
2 -> 4 [ label="1" ];
2 -> 5 [ label="7" ];
3 -> 2 [ label="0.09" ];
4 -> 1 [ label="2" ];
4 -> 3 [ label="-5" ];
5 -> 4 [ label="6" ];
}

QUESTION: How can I change this python code to ask GraphViz to color an edge RED if its weight is less than a specific number (e.g., 0.5), such as the edge from node 3 to 2 (with a weight of 0.09)? And more generally is there a good place to learn much more about how to write python code to create all kinds of DOT files for GraphViz, and to see good examples? Thanks Tom99

回答1:

Graphviz supports color attribute.

Thus, you could modify your code to write out the line

3 -> 2 [ label="0.09" color="red" ];

to color the edge as red.

A simple way to achieve it is to modify the line

out.write('{} -> {} [ label="{}" ];\n'.format(start,end,weight))

into

if weight < 0.5:
    out.write('{} -> {} [ label="{}" color="red" ];\n'.format(start,end,weight))
else:
    out.write('{} -> {} [ label="{}" ];\n'.format(start,end,weight))