graphviz: circular layout while preserving node order

前端 未结 2 685
春和景丽
春和景丽 2020-12-29 11:48

Hey
I want to plot a graph of 128 nodes (labeled 1 to 128) in graphviz using circular layout. Circo does this, but I want the nodes to be placed in order of their label

2条回答
  •  一个人的身影
    2020-12-29 12:16

    Generating your own node positions is the best solution outside of coming up with a better algorithm or adding weighting to circo by altering the graphviz source.

    However, it does defeat the purpose of generating arbitrary graphs with graphviz. This script will use graphviz itself to generate a circle of arbitrary size with user defined formatting, hardcode the position, and then add edges across the center.

    #!/bin/bash
    # loopgen.sh- generates a plain graphviz loop then hardcodes it and adds to it
    # input file format -
    #   num of nodes
    #   prefixes for the generated file (format information, labels)
    #   (blank)
    #   postfixes for the final file (extra connections, inputscale)
    # output - graph with nodes0 to nodex
    file=$(<$1)
    # trim filename to function name
    fun=${1##*/}
    fun=${fun%%.*}
    # gen is generation function
    gen="digraph $fun
    {
        layout=circo;"
    # fin is final function
    fin=""
    # get the number of inputs
    num=$(head -n 1 <<< "$file")
    if [ $num -lt 2 ]; then
        echo "Bad number of inputs."
        exit -1
    fi
    # increment the lines of the file
    file=$(tail -n +2 <<< "$file")
    # add all lines up to the first blank line
    gen="$gen
        $(printf "$file" | awk '!p;/^$/{p=1}')"
    # remove all lines before the first blank line
    file=$(printf "$file" | awk '/^$/{p=1}p')
    # begin producing character-based nodes
    i=1
    gen="$gen
        node0 "
    while [ $i -lt $num ]; do
        gen="$gen -> node$i"
        let i=i+1
    done
    #finish the loop
    gen="$gen -> node0;
    }"
    # generate, replace circo layout reference, make positions absolute
    gen=$(printf "$gen" | dot |
    sed -e 's/layout=circo/layout=neato/' -e 's/\(pos=".*\)"/\1!"/g')
    # remove trailing brace
    gen=$(printf "$gen" | head -n -1)
    
    fin="/* generated with loopgen.sh */
        $gen
        $file
    }"
    
    printf "$fin"
    exit 0
    

    Here is an example file.

    6
    node0 [label="bop it"];
    node1 [label="twist it"];
    node2 [label="pull it"];
    node3 [label="flick it"];
    node4 [label="spin it"];
    node5 [label="throw it away"];
    
    node2 -> node5 [constraint=false,weight=0];
    // this keeps the program from running out of memory
    inputscale=72
    

    Running

    loopgen.sh input | neato -Tpng > output.png
    

    Results in

    output.png

    Where normally, the same layout would result in

    malformed.png

提交回复
热议问题