7
$\begingroup$

I have a graph G, and I wish to individually highlight and color the different connected components of a graph. It is simple enough to do this for one component:

HighlightGraph[G, ConnectedComponents[G][[2]]]

But how does one do this for multiple components? I'd ideally like to be able to pass a color string to specify each highlighted component, something like componentColorString = { Blue, Green, Red,...}. Is this possible?

$\endgroup$
2
  • 2
    $\begingroup$ HighlightGraph[g, Subgraph[g, #] & /@ ConnectedComponents[g]] will highlight all components, each with a different colour. $\endgroup$
    – Szabolcs
    Commented Sep 9, 2013 at 14:24
  • $\begingroup$ @Szabolcs That's a great command. Can I also specify or randomize the colour each time I run it? $\endgroup$
    – nvori
    Commented Sep 10, 2013 at 5:05

1 Answer 1

7
$\begingroup$

You can iterate through the vertex-, and edgelists of connected components:

SeedRandom@11;
g = RandomGraph[{15, 20}, DirectedEdges -> True, 
   EdgeStyle -> [email protected], VertexLabels -> "Name", 
   VertexSize -> [email protected], ImageSize -> 300, ImagePadding -> 10];
conn = ConnectedComponents[g]
{nodes, edges} = Transpose[{VertexList@#, EdgeList@#} &@Subgraph[g, #] & /@ conn];

SetProperty[g, {
  VertexStyle -> 
    Join @@ Table[Thread[nodes[[i]] -> Hue[i/Length@nodes]], {i, Length@nodes}],
  EdgeStyle -> 
    Join @@ Table[Thread[edges[[i]] -> Hue[i/Length@edges, 1., .7]], {i, Length@edges}]
  }]
 {{1}, {3, 7, 8, 11, 12}, {2}, {13, 14}, {15}, {4, 9}, {6}, {5}, {10}}

enter image description here

The same in a Manipulate, showing one connected subgraph at a time:

Manipulate[
 SetProperty[g, {
   VertexStyle -> Thread[nodes[[i]] -> Hue[i/Length@nodes]],
   EdgeStyle -> Thread[edges[[i]] -> Hue[i/Length@edges, 1., .7]],
   PlotLabel -> Row@{"component vertices: ", conn[[i]]}
   }],
 {{i, 1, "component #"}, 1, Length@conn, 1, Appearance -> "Labeled"}]

enter image description here

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.