Search code examples
gnuplot

How to avoid the drawing of non consecutive time series values using cumulative y values in a with lines plot


For this data:

02/29/2020|2
03/01/2020|1
03/06/2020|1
03/07/2020|1
03/11/2020|5
03/12/2020|3

how can you graph something like this:

sample graph

As you can see, my x time data jumps from March 7 to March 11, so a simple with lines will connect point March 7 to point March 11, I don't want that behaviour. Finally, how can you plot so that the x and y pairs are like this

02/29/2020|2
03/01/2020|3
03/06/2020|4
03/07/2020|5
03/11/2020|10
03/12/2020|13

where y keeps adding its previous values:


Solution

  • Can you add empty lines into your data? Then you could do it like this:

    Code:

    ### plot cumulated data over time
    reset session
    
    myTimeFmt = "%m/%d/%Y"
    set datafile separator "|"
    
    $Data <<EOD
    02/29/2020|2
    03/01/2020|1
    
    03/06/2020|1
    03/07/2020|1
    
    03/11/2020|5
    03/12/2020|3
    EOD
    
    set format x "%m/%d" time
    set style line 1 pt 7 lc rgb "red"
    set yrange [0:]
    set key top left
    
    mySum = 0
    plot $Data u (timecolumn(1,myTimeFmt)):(mySum=mySum+$2) w lp ls 1 title "cumulative"
    ### end of code
    

    Result:

    enter image description here

    Addition:

    If you need to insert emtpy lines between non-consecutive days, you can do this also with gnuplot.

    ### plot cumulated data over time (+ insert emtpy line after non-consecutive days)
    reset session
    
    myTimeFmt = "%m/%d/%Y"
    set datafile separator "|"
    
    Data = "$Data"          # if your data is in a file
    # Data = "'Data.dat'"   # uncomment this line and enter your filename
                            # and skip the following datablock
    $Data <<EOD
    02/29/2020|2
    03/01/2020|1
    03/06/2020|1
    03/07/2020|1
    03/11/2020|5
    03/12/2020|3
    EOD
    
    # create data with whitespace as column separator
    set table $Data2
        plot @Data u (strcol(1)):2 w table
    unset table
    
    # with emtpy line between two non-consecutive days
    set print $Data3
        do for [i=1:|$Data2|-1] {
            if (strptime(myTimeFmt,word($Data2[i+1],1)) > \
                strptime(myTimeFmt,word($Data2[i],1))+86400) \
               {print $Data2[i]; print '' }
            else {print $Data2[i]}
        }
        print $Data2[|$Data2|]
    set print
    print $Data3
    
    set datafile separator whitespace
    set format x "%m/%d" time
    set style line 1 pt 7 lc rgb "red"
    set yrange [0:]
    set key top left
    
    mySum = 0
    plot $Data3 u (timecolumn(1,myTimeFmt)):(mySum=mySum+$2) w lp ls 1 title "cumulative"
    ### end of code
    

    Result: (same as above)