Search code examples
gnuplot

gnuplot: how to draw a set of triangles from a file?


In gnuplot, we can set object polygon to draw a polygon, including triangles, given its coordinates.

But how to do draw a set of triangles whose coordinates are stored in a file where each line is in the format <x1> <y1> <x2> <y2> <x3> <y3>?

As for rectrangles/circles, this task can be done using plot and with boxxy/with circles options, but there is no with triangles option in gnuplot.

A possible solution is to use with vectors by drawing each edge, but it is a bit complicated and this method does not support color filling.


Solution

  • I cannot think of a way to do this in one step; the data format does not match any of gnuplot's plotting styles.

    One approach is to transform the data via a temporary file. Here is an example that works in version 5.2 and newer. If you are using a newer gnuplot then you could substitute with polygons for with filledcurves closed.

    $DATA << EOD
    1 1 2 2 3 1
    11 11 14 14 17 11
    21 21 22 22 23 21
    15 5 16 6 17 5
    6 6 7 7 8 6
    EOD
    
    set table "temp.dat"
    plot $DATA using (sprintf("%g %g\n %g %g\n %g %g\n \n",$1,$2,$3,$4,$5,$6)) with table
    unset table
    
    unset key
    set style fill solid noborder
    plot "temp.dat" using 1:2 with filledcurves closed fillcolor "forest-green"
    

    enter image description here

    Note: I was originally going to show use of a temporary datablock rather than an intermediate temporary file, but it this doesn't work because the formatted output from with table does not translate the newline characters \n into empty datablock lines.

    Edit (show variable color)

    The extra data field containing a RGB color must be present in every input line of the reformatted data, but only the value from the first vertex of each polygon is used. The sprintf format in this example has been modified to reproduce the color (NB: hexadecimal integer value) from the original data file accordingly, with zeros for the dummy values in the remaining polygon vertices.

    $DATA << EOD
    1 1 2 2 3 1             0x00ffff
    11 11 14 14 17 11       0x191970
    21 21 22 22 23 21       0x2e8b57
    15 5 16 6 17 5          0xffc020
    6 6 7 7 8 6             0x8b000
    EOD
    
    set table "temp.dat"
    plot $DATA using (sprintf("%g %g 0x%x\n %g %g 0\n %g %g 0\n \n",$1,$2,int($7),$3,$4,$5,$6)) with table
    unset table
    
    unset key
    set style fill solid noborder
    plot "temp.dat" using 1:2:3 with filledcurves closed fillcolor rgb variable
    

    enter image description here