#!/usr/bin/gnuplot -persist
#
#    
#    	G N U P L O T
#    	Version 4.6 patchlevel 6    last modified September 2014
#    	Build System: Linux x86_64
#    
#    	Copyright (C) 1986-1993, 1998, 2004, 2007-2014
#    	Thomas Williams, Colin Kelley and many others
#    
#    	gnuplot home:     http://www.gnuplot.info
#    	faq, bugs, etc:   type "help FAQ"
#    	immediate help:   type "help"  (plot window: hit 'h')

set title "Seasonal phenomenon, highlighted wrapping around each year"

set border 3
set grid xtics back
set nokey
set rmargin 8

set xdata time
set timefmt "%Y-%m-%d"
set format x "%s"
set xtics out nomirror rotate by -45
set ytics out nomirror 1

# Dummy plot to gather some stats from the dataset
set terminal unknown
plot 'data.dat' using 1:2

xmin = GPVAL_DATA_X_MIN
xmax = GPVAL_DATA_X_MAX

# Plot over 12 months
set xrange[0:12]
set xtics ( \
  'Jan'  0, \
  'Feb'  1, \
  'Mar'  2, \
  'Apr'  3, \
  'May'  4, \
  'Jun'  5, \
  'Jul'  6, \
  'Aug'  7, \
  'Sep'  8, \
  'Oct'  9, \
  'Nov' 10, \
  'Dec' 11, \
  ''    12)

year_min = tm_year(xmin)
year_max = tm_year(xmax)

set cbrange [year_min:year_max + 1]

# Generate colorbox labels programmatically
cblabels = 'set cbtics ( '
do for [i=year_min:year_max] {
   cblabels = cblabels . '"' . i .'" ' . i .','
}
cblabels = cblabels . '"" ' . int(year_max + 1) .','
cblabels = cblabels . ' )'
eval(cblabels)

# The value 12 works well with the default colorbox height
cbtics_offset = 12 / (year_max - year_min)
set cbtics offset 0,+cbtics_offset

set palette rgbformulae 31,-11,32
set palette maxcolors (year_max - year_min + 1)

# Scale the data so that one year covers the xrange of 12 months,
# this allows samples in the same time of the year to be at the abscissa.
one_year = 60 * 60 * 24 * 365.25
scale_date_to_month(x) = (int(x) % int(one_year)) / one_year * 12

# With this hacky-ish wrap() function we loose some points when the data wraps
# around, but AFAIK this is unavoidable without preprocessing the data.
#
# Value wraps around if the year changes between 'new' and 'old'.
year_wrap(old, new) = tm_year(old) == tm_year(new) ? scale_date_to_month(new) : NaN

if (GPVAL_VERSION < 5.0) \
  tcol(x) = timecolumn(x); \
else \
  tcol(x) = timecolumn(x, "%Y-%m-%d")

set terminal qt 0
#set terminal png notransparent nocrop truecolor rounded enhanced font "arial,8" fontscale 1.0
#set output 'modular_cartesian.png'

saved = -1
plot \
  'data.dat' using (prev=saved, saved=tcol(1), year_wrap(prev, saved)):2:(tm_year(tcol(1))) with lines lc palette lw 1.5