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.

Say I have a graph Gtest, which has multiple disconnected components. I found that I can isolate individual components while retaining vertex coordinate specifications if I use VertexDelete in the manner of:

VertexDelete[Gtest, ConnectedComponents[Gtest][[2]]]

Here assuming that Gtest has only two connected components. However, this seems like a ridiculous way of proceeding. Is there a one-liner that will let me make a list of graphs Glist = {g1, g2, g3, ...} where each $g_i$ corresponds to a particular connected graph in G? How can I do this while respecting my original vertex coordinate assignments for G?

share|improve this question
add comment

2 Answers

There is no guarantee VertexDelete will preserve VertexCoordinates. However you can use Subgraph and manually provide the old coordinates:

connectedSubgraphs[g_Graph] :=
 Module[{
   vc = Transpose[{
           VertexList[g],
           VertexCoordinates /. AbsoluteOptions[g, VertexCoordinates]}]
   },
  Subgraph[g, #,
     (* Exctract the coordinates for vertices in the component *)
     VertexCoordinates -> Cases[vc, {v_ /; MemberQ[#, v], c_} :> c]
     ] & /@ ConnectedComponents[g]
  ]

If you have v9 you can use GraphEmbedding to get the coordinates instead of AbsoluteOptions

Note that this wont preserve any other options:

g = Graph[{
    10 \[UndirectedEdge] 11, 11 \[UndirectedEdge] 12, 
    12 \[UndirectedEdge] 13, 13 \[UndirectedEdge] 10,
    1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3,
    4 \[UndirectedEdge] 5, 5 \[UndirectedEdge] 6,
    7 \[UndirectedEdge] 8, 8 \[UndirectedEdge] 9},
   VertexStyle -> {1 -> Red, 2 -> Blue, 3 -> Green},
   VertexSize -> {1 -> Large}];
connectedSubgraphs[g] // Row

graphs

But it can be extended as is shown in Preserving labels when using graph functions

Disclaimer: I don't know if ConnectedComponents and Subgraph always preserve the vertex order, if they don't the subgraphs will be given incorrect coordinates.

share|improve this answer
add comment

A more straightforward way is to use SetProperty on the resulting graph to restore the original vertex coordinates.

g = Graph[{2 -> 4, 1 -> 2, 2 -> 3, 3 -> 1, 5 -> 4, 4 -> 6, 1 -> 7, 2 -> 7},
          VertexLabels -> "Name", ImagePadding -> 10];
coord = Thread[VertexList@g -> (VertexCoordinates /. AbsoluteOptions@g)];
g2 = VertexDelete[g, {5, 1}];
g3 = SetProperty[g2, VertexCoordinates -> (VertexList@g2 /. coord)];

Grid[{{"original", "{5, 1} deleted", "coordinates restored"}, {g, g2, g3}}]

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.