1
$\begingroup$

I'd like to write a program to draw a graph taking as an input the size of the layers and the edges of the graph. e.g. For edges={} and Layers={3,3,5,1} I'd expect something like this

I've used this code to generate the plot but (i) of course I'm just using the 'trick' of coloring the edges the same as the background just to put the vertices where I want them - which it's computationally expensive to do, especially for bigger numbers of vertices, and (ii) I don't really know how to specify the edges now.

Layers = {3, 3, 5, 1} // Sort[#, Greater] &;
Graph[CompleteGraph[Total[Layers], EdgeStyle -> White], VertexSize -> Large, GraphLayout -> {"MultipartiteEmbedding", "VertexPartition" -> Layers}]

Then, my question reduces to: (i) Is there a better way to force the size of the layers, and (ii) how to specify the edges within this new layout.

$\endgroup$
3
$\begingroup$
Layers = {3, 3, 5, 1} // Sort[#, Greater] &;

g0 = Graph[Range @ Total@Layers, {}, VertexSize -> Large, 
 VertexCoordinates -> GraphEmbedding[CycleGraph[Total[Layers]],
     {"MultipartiteEmbedding", "VertexPartition" -> Layers}]]

enter image description here

EdgeList  @ g0
 {}

Not sure if I understand "how to specify the edges within this new layout" bit; perhaps something like the following?

Graph[EdgeAdd[g0, {2 -> 5, 3 -> 8, 7 -> 12}], 
 EdgeShapeFunction -> GraphElementData[{"CurvedArc", "Curvature" -> 2/3}], 
 VertexLabels -> Placed["Name", Center]]

enter image description here

Update: You can also construct a multi-partite layout function and use it to specify vertex coordinates:

ClearAll[mPartiteLayout]
mPartiteLayout[s_: N[GoldenRatio]] := Module[{xc = Subdivide[Length@# - 1],
     yc = Rescale[Range[(1 - #)/2, (# - 1)/2] & /@ #]/s},
    Join @@ (Thread /@ Transpose[{xc, yc}])] &;

Graph[Range @ Total @ Layers, {}, VertexSize -> Large, 
 VertexCoordinates -> mPartiteLayout[] @ Layers]

enter image description here

SeedRandom[77];
nl = RandomInteger[{5, 20}, 12];
Graph[Range @ Total @ #, {}, VertexSize -> Large, 
    VertexCoordinates -> mPartiteLayout[] @ #, PlotLabel -> #, 
    ImageSize -> 250] & /@ (RandomInteger[{1, 10}, #] & /@ nl) // 
 Grid[Partition[#, 4], Dividers -> All] &

enter image description here

$\endgroup$
1
  • 2
    $\begingroup$ Yeap, just like that. Also, those CurvedArcs are a nice detail, they look nice, thanks. $\endgroup$ – JuanC97 Oct 10 '20 at 0:59

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.