Search code examples
graphtreegnuplot

How to plot a tree/graph/web with weighted edges in Gnuplot?


i am plotting a tree in gnuplot as discussed here (How to plot tree/graph/web data on gnuplot?). However, i would like to include the edges weight of the tree, i.e. for each edge i have a number (e.g. 10, 20, 30, 40) that represents the edge weight. The figure below shows in red the edges weight that i want to plot in gnuplot (i added this using power point).

Can anyone tell me how to plot edges with weight in gnuplot?

enter image description here


Solution

  • I would propose a slight variation on the answer which you mention in your question. Let's assume that the coordinates of the vertices are stored in a file pnts.dat as follows:

    0   5   10
    1   20  20
    2   15  15
    3   30  30
    4   40  10
    

    Here, the first column records the corresponding label, while second and third columns contain the x- and y-coordinate, respectively.

    The edges could be defined in a separate file edges.dat as:

    0   1   30  0   1
    1   2   40  0   -2
    1   4   20  0   1
    1   3   10  0   1
    

    Here, the first two column contain the point indices (they refer to the first column of pnts.dat). The third column records the weight of a particular edge. Finally, the last two columns contain the x,y displacement of the generated associated label.

    With this, the Gnuplot script could look like:

    set xr [0:50]   
    set yr [0:50]
    
    set size square   
    
    flePnts = 'pnts.dat'
    fleEdges = 'edges.dat'
    
    loadEdges = sprintf('< gawk '' \
        FNR==NR{x[$1]=$2;y[$1]=$3;next;} \
        {printf "%%f\t%%f\n%%f\t%%f\n\n", x[$1], y[$1], x[$2], y[$2];} \
    '' %s %s', flePnts, fleEdges); 
    
    loadWeights = sprintf('< gawk '' \
        FNR==NR{x[$1]=$2;y[$1]=$3;next;} \
        {printf "%%f\t%%f\t%%s\n", (x[$1]+x[$2])/2 + $4, (y[$1]+y[$2])/2 + $5, $3} \
    '' %s %s', flePnts, fleEdges);
    
    plot \
        loadEdges using 1:2 with lines lc rgb "black" lw 2 notitle, \
        flePnts using 2:3:(0.6) with circles fill solid lc rgb "black" notitle, \
        flePnts using 2:3:1 with labels tc rgb "white" font "Arial Bold" notitle, \
        loadWeights using 1:2:3 with labels tc rgb "red" center font "Arial Bold" notitle
    
    1. the loadEdges command invokes gawk in order to generate for all edges the corresponding pairs of x/y coordinates (delimited by a blank line)
    2. loadWeights calculates for each edge the middle point and places a label at these coordinates (taking into account the required offset)

    Finally, one obtains: enter image description here