Search code examples
datetimegnuplot

Timefmt for day of the year in gnuplot


I am using gnuplot 5.4.4

How can I make the pseudocolumn 0 show the day of the year and properly handle this with xdata time?

A minimal working example that shows the issue:

plot filename u 0:1

Each line of the file represents a day of the year starting on Jan 1st. Therefore I set the x axis to show time and set the time format specifier to %j (day of the year 1-365) as per the manual.

set xdata time; set timefmt "%j"; replot

In view of the result (see attached minimal working example figure) it looks like the special column $0 is interpreted as a minute rather than a day of the year. Reformatting the xtics label with

   set format x "%j" 

does not solve the problem (see attached figure).

minimal working example

Minimal working example with set format x "%j"


Solution

  • Without an explanation why the following does not give the expected result,

    reset session
    set xdata time
    set timefmt "%j"
    set format x "%j"
    set samples 366
    
    plot '+' u 0:1
    

    I'm just speculating that "%j" might not work as input format and gnuplot still thinks that input is the default "%s", i.e. seconds since the Unix epoch (1970-01-01 00:00 UTC). Hence, in order to get the desired output, multiply the pseudocolumn $0 with number of seconds per day, i.e. 24*3600.

    reset session
    set xdata time
    set timefmt "%j"
    set format x "%j"
    set samples 366
    
    plot '+' u ($0*24*3600):1
    

    Result:

    enter image description here

    Addition:

    If you handle time in seconds, 0 will be Jan. 1st 1970. So, if the leap year is important for you, you need to convert your pseudocolumn $0 into your "correct" year, e.g. 2024, by adding an offset t0 = strptime("%Y",2024"). Check help strptime.

    The example below does that. Actually, there, set xdata time and set timefmt "%j" are not used, but set format x "%j% timedate" instead, but then you have to give the xrange in seconds as well using strptime(). The second plot is zoomed into end of year 2024 and you can see that there are 366 days.

    Script:

    ### day of the year for certain year
    reset session
    
    # create some test data
    set table $Data
        set samples 400
        plot '+' u (cos($0*0.025)) w table
    unset table
    
    t(col) = column(col)*24*3600 + strptime("%Y","2024")
    
    set multiplot layout 2,1
    
        set format x "%j" timedate
        plot $Data u (t(0)):1 w p pt 7 lc "red"
    
        set xrange[strptime("%Y-%m-%d","2024-12-26"):strptime("%Y-%m-%d","2025-01-04")]
        replot
    unset multiplot
    ### end of script
    

    Result:

    enter image description here