3
$\begingroup$

I am trying to draw a graph in a tree-like form. I can't use TreeGraph because what I am drawing is not properly a tree (has loops) so TreeGraph won't draw it. Here is the code:

Graph[{1 -> 3, 1 -> 4, 1 -> 5, 3 -> 7, 3 -> 8, 4 -> 6, 4 -> 7, 5 -> 8,6 -> 12, 7 -> 12, 8 -> 12},
GraphLayout -> "LayeredEmbedding",
VertexLabels -> "Name"]

and this is the output:

enter image description here

My question: is it possible to move vertex 6 to the left of vertex 7, i.e. to achieve a LayeredLeft effect?

If vertex 3 were the same distance from 4 as 4 is from 5 that would be even better, i.e. some kind of grid effect.

Thanks in advance

$\endgroup$
2
$\begingroup$

You can manually set the VertexCoordinates. The order of the coordinates are

Graph[
  {1 -> 3, 1 -> 4, 1 -> 5, 3 -> 7, 3 -> 8, 4 -> 6, 4 -> 7, 5 -> 8, 6 -> 12, 
   7 -> 12, 8 -> 12}] // VertexList

{1, 3, 4, 5, 7, 8, 6, 12}

Graph[
 {1 -> 3, 1 -> 4, 1 -> 5, 3 -> 7, 3 -> 8, 4 -> 6, 4 -> 7, 5 -> 8, 6 -> 12, 
  7 -> 12, 8 -> 12},
 VertexLabels -> "Name",
 VertexCoordinates -> {
   {1, 1.5}, {1, 1}, {0, 1}, {2, 1}, {1, .5}, {2, .5}, {0, .5}, {1, 0}}]

enter image description here

Alternatively, change the order of entry of the edges

Graph[{1 -> 4, 4 -> 6, 4 -> 7, 1 -> 3, 1 -> 5, 3 -> 7, 3 -> 8, 5 -> 8, 
  6 -> 12, 7 -> 12, 8 -> 12},
 VertexLabels -> "Name"]

enter image description here

$\endgroup$
  • $\begingroup$ Excellent, thanks a lot! $\endgroup$ – pdini Dec 21 '14 at 0:08
3
$\begingroup$

Simply use Sorted vertex list as the first argument of Graph to avoid manual modification of vertex coordinates or of the edge list:

g1 = Graph[{1 -> 3, 1 -> 4, 1 -> 5, 3 -> 7, 3 -> 8, 4 -> 6, 4 -> 7, 
    5 -> 8, 6 -> 12, 7 -> 12, 8 -> 12}, 
   GraphLayout -> "LayeredEmbedding", VertexLabels -> "Name", ImageSize -> 300];

g2 = Graph[Sort[VertexList[g1]], EdgeList[g1], VertexLabels -> "Name", ImageSize -> 300];

Row[{g1, g2}, Spacer[10]]

enter image description here

$\endgroup$
  • $\begingroup$ Nice, that's simple and elegant, thank you. $\endgroup$ – pdini Aug 5 '17 at 7:05

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.