Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
HighlightGraph[g, Subgraph[g, #] & /@ ConnectedComponents[g]] will highlight all components, each with a different colour. –  Szabolcs Sep 9 '13 at 14:24
    
@Szabolcs That's a great command. Can I also specify or randomize the colour each time I run it? –  nvori Sep 10 '13 at 5:05
add comment

1 Answer

up vote 3 down vote accepted

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

SeedRandom@11;
g = RandomGraph[{15, 20}, DirectedEdges -> True, 
   EdgeStyle -> GrayLevel@.8, VertexLabels -> "Name", 
   VertexSize -> Scaled@.03, 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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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