Search code examples
gnuplot

Fill colour between two smooth lines drawn by data points in gnuplot


I have file “data.txt” containing three columns. Column 1 is for x axis. I want to draw smooth curves corresponding to data points of column 2 and 3 and then want to fill colour between these two lines.

File content is;

10    -1.3     1.1
20    -0.956   0.933
50    -0.761   0.684
80    -0.523   0.439
110   -0.227   0.20
130   -0.07    0.06

My script lines are,

plot “data.txt” u 1:2 smooth bezier w filledcurves above,\
“data.txt” u 1:3 smooth bezier w filledcurves below

But I’m not getting desired shaded plot.


Solution

  • I guess you have two challenges here:

    • you cannot smooth and fill at the same time
    • you can only fill between two columns of the same dataset or file

    One possible way would be the following:

    • plot the data smooth bezier into a table $Smooth
    • N is the number of lines the combined smoothed data $Smooth
    • merge these smoothed data by using line 1 and 1+N/2, line 2 and 2+N/2, etc. into a dataset $Paste
    • for the fill you then have to use columns 1, 2 and 5

    Script:

    ### fill area between smoothed curves
    reset session
    
    $Data <<EOD
      0    0   90
     10   10   50
     50   20   40
     80   50   60
    100   30   50
    EOD
    
    set table $Smooth
        set samples 20
        plot $Data u 1:2 smooth bezier
        plot $Data u 1:3 smooth bezier
    unset table
    
    set print $Paste
        N = |$Smooth|
        do for [i=1:N/2] {
            print $Smooth[i].$Smooth[i+N/2]
        }
    set print
    
    plot $Data u 1:2:3  w filledcurves  lc rgb 0xcc0000ff ti "fill between data", \
            '' u 1:2    w lp pt 7       lc "red"          ti "original data", \
            '' u 1:3    w lp pt 7       lc "red"          notitle, \
         $Smooth u 1:2  w lp pt 7       lc "green"        ti "smoothed curves", \
         $Paste  u 1:2:5 w filledcurves lc rgb 0xccff0000 ti "fill between smoothed"
    ### end of script
    

    Result:

    enter image description here