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}}
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"}]
HighlightGraph[g, Subgraph[g, #] & /@ ConnectedComponents[g]]
will highlight all components, each with a different colour. $\endgroup$