Search code examples
javascripthtmlmermaid

horizontally align specific nodes in mermaid graph


I have a large mermaid graph. I wanted to print some of the sections vertically rather than horizontally.

I was able to shift some of the groups of the graph downward by adding dashes to the arrows in the mermaid graph code: ----> instead of -->.

Here is a minimial example which shows what I am talking about:

<html lang="en" style="height: auto;">
<head>
</head>

<body>
    <div class="mermaid">
    graph TD;
    A-->B;
    B-->C;
    C-->D;
    C------>E;
    C-------->F;
    C---------->G;
    
    D-->d1;
    D-->d2;
    D-->d3;
    D-->d4;
    
    d2-->dd1;
    d2-->dd2;
    d2-->dd3;
    
    E-->e1;
    E-->e2;
    E-->e3;
    E-->e4;
    
    F-->f1;
    F-->f2;
    F-->f3;
    F-->f4;
    
    G-->g1;
    G-->g2;
    G-->g3;
    G-->g4;
    </div>
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.13.4/mermaid.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/pdfkit@0.10.0/js/pdfkit.standalone.js"></script>
<script src="https://bundle.run/blob-stream@0.1.3"></script>
<script src="https://cdn.jsdelivr.net/npm/svg-to-pdfkit@0.1.8/source.js"></script>

<script>
mermaid.init({
    flowchart: { useMaxWidth: false },
    "theme": "default",
    "themeVariables": {
        "fontFamily": "Helvetica"
    }
}, document.querySelectorAll(".mermaid"));
</script>

The above code produces this image:

enter image description here

<script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.14.0/mermaid.min.js"></script>
<div class="mermaid">
  graph TD;
    A-->B;
    B-->C;
    C-->D;
    C------>E;
    C-------->F;
    C---------->G;
    
    D-->d1;
    D-->d2;
    D-->d3;
    D-->d4;
    
    d2-->dd1;
    d2-->dd2;
    d2-->dd3;
    
    E-->e1;
    E-->e2;
    E-->e3;
    E-->e4;
    
    F-->f1;
    F-->f2;
    F-->f3;
    F-->f4;
    
    G-->g1;
    G-->g2;
    G-->g3;
    G-->g4;
</div>

But there is a lot of wasted space here. I want each section to be vertically below the previous section. Where by sections I mean nodes C, D, E, F, and G. To clarify, I would like nodes C, D, E, F, and G, to have the same horizontal coordinates, and to accomplish that, each should have a lower vertical coordinate.

At the moment node F is placed horizontally after node E's last child, e4. I would like node E to be horizontally the same position as node D, just below all of node E's children.

Is this possible?

Thanks!

Note: I found this answer with a similar title, but the answer does not work on the graph in this example. The answer does not align the nodes horizontally it just shifts things down.


Solution

  • Change the first line of markdown to:

    graph LR;
    

    This stands for 'left-to-right' whereas TD stands for 'top-down'. Now the chart looks like this:

    A left to right graph