gnuplotaxis-labels

Custom gnuplot axis label for time series


The subject whose data I want to display was born 1988-04-20.

I would like to have the X2 axis display the integral ages of the subject thus:

   | x2 label | Corresponding x1 value |
   |----------+------------------------|
   | "18"     | 2006-04-20             |
   | "19"     | 2007-04-20             |
   | "20"     | 2008-04-20             |
   | "21"     | 2009-04-20             |

Script:

reset session;

$Data <<EOD
2006-03-24 150
2007-01-12 147
2007-11-12 149
2007-11-15 142
2008-03-29 166
2008-12-16 173
2009-05-06 170
EOD

birth_date  = "1988-04-20";

set xdata   time;
set timefmt "%Y-%m-%d";
set xtics   format "%Y-\n%m";
set x2label "Age";
set ylabel  "Weight (lbs.)";

plot $Data using 1:2;

Result: age-by-weight.png


Solution

  • There are two ways to plot time data, where I usually prefer the second way.

    set xdata time
    set timefmt "%Y-%m-%d"
    set format x "%Y\n%m"  
    plot $Data u 1:2
    

    or

    set format x "%Y\n%m" timedate
    plot $Data u (timecolumn(1,"%Y-%m-%d")):2
    

    Furthermore, you can link x and x2 axis, check help link. I guess this might be easier with the second way (actually, haven't tried the first way).

    For further reading, check help time/date, help timecolumn and help strptime.

    Script:

    ### plotting date on x1 and age on x2
    reset session
    
    $Data <<EOD
    2006-03-24  150
    2007-01-12  147
    2007-11-12  149
    2007-11-15  142
    2008-03-29  166
    2008-12-16  173
    2009-05-06  170
    EOD
    
    myFmt       = "%Y-%m-%d"
    SecsPerYear = 3600*24*365.25
    birth_date  = strptime(myFmt, "1988-04-20")
    
    set format x "%Y\n%m" timedate
    set xtics nomirror
    set x2tics numeric 0.5 nomirror
    set x2label "Age"
    set ylabel "Weight (lbs.)"
    set grid x,y
    set key noautotitle
    set link x2 via (x-birth_date)/SecsPerYear inverse (x*SecsPerYear+birth_date)
    
    plot $Data u (timecolumn(1,myFmt)):2 w lp pt 7
    ### end of script
    

    Result:

    enter image description here