5
$\begingroup$

Consider the two graphs:

gr1 = Graph[{DirectedEdge[1, 2], DirectedEdge[3, 2]}, EdgeStyle -> Black, VertexLabels -> Table[i -> Subscript[x, i], {i, 3}]]

enter image description here

gr2 = Graph[{DirectedEdge[4, 1], DirectedEdge[1, 5], DirectedEdge[5, 2], DirectedEdge[2, 6], DirectedEdge[6, 3], DirectedEdge[3, 7]}, EdgeStyle -> Red, VertexLabels -> Table[i -> Subscript[x, i], {i, 3}]]

enter image description here

I am looking for a way to display both graphs together, such that they are connected at the shared vertices x1,x2,x3. Ideally, it should look like:

enter image description here

I tried something like GraphPlot[{gr1,gr2}] but this syntax seems flawed. How should I be doing this?

$\endgroup$
4
$\begingroup$

The union can be computed using GraphUnion. It constructs a new graph containing the vertices and edges from both.

Styling and other properties are lost and need to be re-added.

| improve this answer | |
$\endgroup$
  • $\begingroup$ This works well, thanks! But is there a way to force the labeled vertices to be on a straight line, while the other ones go in zig-zag? $\endgroup$ – Kagaratsch Nov 16 '16 at 18:55
  • $\begingroup$ @Kagaratsch I don't know of any automatic way. You can always set vertex coordinates manually, even copy them from the two graphs. But I don't know how to set only some vertex coordinates and leave the rest to an automatic layout. $\endgroup$ – Szabolcs Nov 16 '16 at 19:05
  • 1
    $\begingroup$ @Kagaratsch, maybe GraphUnion[gr1, gr2, VertexLabels -> Table[i -> Subscript[x, i], {i, 3}], GraphLayout -> "MultipartiteEmbedding", EdgeStyle -> Thread[EdgeList[gr1] -> Directive[Thick, Opacity[1], Black]], VertexStyle -> Thread[VertexList[gr1] -> Black], BaseStyle -> Red]? $\endgroup$ – kglr Nov 16 '16 at 22:49
  • $\begingroup$ Wow, this is great, thank you! $\endgroup$ – Kagaratsch Nov 16 '16 at 22:53
2
$\begingroup$
props = {EdgeStyle -> {_ :> Red,  DirectedEdge[1, 2] | DirectedEdge[3, 2] -> Black}, 
   ImagePadding -> 10, 
   VertexLabels -> { j_ :> j, i_ /; i <= 3 :> Subscript[x, i]}, 
   VertexCoordinates -> (Composition[ScalingTransform[{1, .25}], 
       ReflectionTransform[{-1, 0}], RotationTransform[Pi/2]][GraphEmbedding[g2]])};

SetProperty[g2 = SetProperty[GraphUnion[gr1, gr2], 
    GraphLayout -> "MultipartiteEmbedding"], props]

enter image description here

Note: For this particular case, you can also use EdgeAdd[gr2, EdgeList @ gr1] instead of GraphUnion[gr1, gr2].

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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