Graphviz: how to assign the same style to a group

2019-02-05 18:20发布

问题:

I've got a graph that I want graphviz to layout and visualize for me. The graph has 122 edges and 123 nodes. The edges are of 4 different kinds and I want them to be visually distinguishable. However I've not yet decided what would be the best way of doing that, I'd like to play around with the dials a bit. Unfortunately I do not see anything like a "class" or "stylesheet" attribute for edges. I can only set visual attributes individually for every edge (lots of repetition). Perhaps I've missed something? Is there maybe some way after all to add edges to 4 different groups and then style the groups, not each edge individually?

回答1:

To style edges (or nodes) by group rather than individually, use subgraph.

like so:

digraph G {

node [style=filled,color="#5D8AA8", fillcolor="#5D8AA8"];

subgraph c1 {
    edge [color="#004225", arrowsize="0.6", penwidth="1"];
    "node 1" -> "node 3";
    "node 5" -> "node 7";
    "node 1" -> "node 2"; 
    label = "";
}

subgraph c2 {
    edge [color="#FBEC5D", arrowsize="1.2", penwidth="3"];
    "node 2" -> "node 4";
    "node 4" -> "node 6";
    "node 3" -> "node 5";
    "node 6" -> "node 8"; 
    label = "";

}

begin -> "node 1";
start -> "node 2";
"node 1" -> "node 4"
"node 2" -> "node 6";

start [shape=diamond];}

So if you put the code above in a file w/ a ".dot" extension; then render it in graphviz,, you'll see three different types of edges, appearance-wise.

One type is the just the default (color=black, thickness=1, etc.)--i.e., these edges not assigned to a subgraph.

The other two types of edges(a thin, dark-green group, and a thick, bright-yellow group) are styled based on assignment to one of two subgraph clusters.

Subgraph is often used to visually highlight a node cluster (i.e., to distinguish a particular contiguous 'group' of nodes from the rest of the nodes in the graph); however, there is no requirement (as you can see from my example) that the edges you chose to style by assignment to a given subgraph, belong to a contiguous 'group' of nodes--you can designate any edges you wish for assignment to a given sub-graph.)

to me, styling nodes by group is analogous to the HTML practice of defining a class and assigning it to a collection of divs in HTML markup



回答2:

While @doug's answer is correct (use subgraphs to assign similar style to groups of objects), I believe my example is better:

digraph G {                                                                     
  compound=true;
  subgraph columns {
    c0r0 -> c0r1;
    c0r1 -> c0r2;
    c1r0 -> c1r1;
    c1r1 -> c1r2;
    c2r0 -> c2r1;
    c2r1 -> c2r2;
  }
  subgraph rows {
    edge [color=red, constraint=false];
    c0r0 -> c1r0;
    c1r0 -> c2r0;
    c0r1 -> c1r1;
    c1r1 -> c2r1;
    c0r2 -> c1r2;
    c1r2 -> c2r2;
  }
}


cat square-digraph.dot | dot -Tsvg -o square-digraph.svg