view scripts/time/datetick.m @ 14363:f3d52523cde1

Use Octave coding conventions in all m-file %!test blocks * wavread.m, acosd.m, acot.m, acotd.m, acoth.m, acsc.m, acscd.m, acsch.m, asec.m, asecd.m, asech.m, asind.m, atand.m, cosd.m, cot.m, cotd.m, coth.m, csc.m, cscd.m, csch.m, sec.m, secd.m, sech.m, sind.m, tand.m, accumarray.m, accumdim.m, bitcmp.m, bitget.m, bitset.m, blkdiag.m, cart2pol.m, cart2sph.m, celldisp.m, chop.m, circshift.m, colon.m, common_size.m, cplxpair.m, cumtrapz.m, curl.m, dblquad.m, deal.m, divergence.m, flipdim.m, fliplr.m, flipud.m, genvarname.m, gradient.m, idivide.m, int2str.m, interp1.m, interp1q.m, interp2.m, interp3.m, interpft.m, interpn.m, isa.m, isdir.m, isequal.m, isequalwithequalnans.m, issquare.m, logspace.m, nargchk.m, narginchk.m, nargoutchk.m, nextpow2.m, nthargout.m, num2str.m, pol2cart.m, polyarea.m, postpad.m, prepad.m, profile.m, profshow.m, quadgk.m, quadv.m, randi.m, rat.m, repmat.m, rot90.m, rotdim.m, shift.m, shiftdim.m, sph2cart.m, structfun.m, trapz.m, triplequad.m, convhull.m, dsearch.m, dsearchn.m, griddata3.m, griddatan.m, rectint.m, tsearchn.m, __makeinfo__.m, doc.m, get_first_help_sentence.m, help.m, type.m, unimplemented.m, which.m, imread.m, imwrite.m, dlmwrite.m, fileread.m, is_valid_file_id.m, strread.m, textread.m, textscan.m, commutation_matrix.m, cond.m, condest.m, cross.m, duplication_matrix.m, expm.m, housh.m, isdefinite.m, ishermitian.m, issymmetric.m, logm.m, normest.m, null.m, onenormest.m, orth.m, planerot.m, qzhess.m, rank.m, rref.m, trace.m, vech.m, ans.m, bincoeff.m, bug_report.m, bzip2.m, comma.m, compare_versions.m, computer.m, edit.m, fileparts.m, fullfile.m, getfield.m, gzip.m, info.m, inputname.m, isappdata.m, isdeployed.m, ismac.m, ispc.m, isunix.m, list_primes.m, ls.m, mexext.m, namelengthmax.m, news.m, orderfields.m, paren.m, recycle.m, rmappdata.m, semicolon.m, setappdata.m, setfield.m, substruct.m, symvar.m, ver.m, version.m, warning_ids.m, xor.m, fminbnd.m, fsolve.m, fzero.m, lsqnonneg.m, optimset.m, pqpnonneg.m, sqp.m, matlabroot.m, __gnuplot_drawnow__.m, __plt_get_axis_arg__.m, ancestor.m, cla.m, clf.m, close.m, colorbar.m, colstyle.m, comet3.m, contourc.m, figure.m, gca.m, gcbf.m, gcbo.m, gcf.m, ginput.m, graphics_toolkit.m, gtext.m, hggroup.m, hist.m, hold.m, isfigure.m, ishghandle.m, ishold.m, isocolors.m, isonormals.m, isosurface.m, isprop.m, legend.m, line.m, loglog.m, loglogerr.m, meshgrid.m, ndgrid.m, newplot.m, orient.m, patch.m, plot3.m, plotyy.m, __print_parse_opts__.m, quiver3.m, refreshdata.m, ribbon.m, semilogx.m, semilogxerr.m, semilogy.m, stem.m, stem3.m, subplot.m, title.m, uigetfile.m, view.m, whitebg.m, compan.m, conv.m, deconv.m, mkpp.m, mpoles.m, pchip.m, poly.m, polyaffine.m, polyder.m, polyfit.m, polygcd.m, polyint.m, polyout.m, polyval.m, polyvalm.m, ppder.m, ppint.m, ppjumps.m, ppval.m, residue.m, roots.m, spline.m, intersect.m, ismember.m, powerset.m, setdiff.m, setxor.m, union.m, unique.m, autoreg_matrix.m, bartlett.m, blackman.m, detrend.m, fftconv.m, fftfilt.m, fftshift.m, freqz.m, hamming.m, hanning.m, ifftshift.m, sinc.m, sinetone.m, sinewave.m, unwrap.m, bicg.m, bicgstab.m, gmres.m, gplot.m, nonzeros.m, pcg.m, pcr.m, spaugment.m, spconvert.m, spdiags.m, speye.m, spfun.m, spones.m, sprand.m, sprandsym.m, spstats.m, spy.m, svds.m, treelayout.m, bessel.m, beta.m, betaln.m, factor.m, factorial.m, isprime.m, lcm.m, legendre.m, nchoosek.m, nthroot.m, perms.m, pow2.m, primes.m, reallog.m, realpow.m, realsqrt.m, hadamard.m, hankel.m, hilb.m, invhilb.m, magic.m, rosser.m, vander.m, __finish__.m, center.m, cloglog.m, corr.m, cov.m, gls.m, histc.m, iqr.m, kendall.m, kurtosis.m, logit.m, mahalanobis.m, mean.m, meansq.m, median.m, mode.m, moment.m, ols.m, ppplot.m, prctile.m, probit.m, quantile.m, range.m, ranks.m, run_count.m, runlength.m, skewness.m, spearman.m, statistics.m, std.m, table.m, var.m, zscore.m, betacdf.m, betainv.m, betapdf.m, betarnd.m, binocdf.m, binoinv.m, binopdf.m, binornd.m, cauchy_cdf.m, cauchy_inv.m, cauchy_pdf.m, cauchy_rnd.m, chi2cdf.m, chi2inv.m, chi2pdf.m, chi2rnd.m, discrete_cdf.m, discrete_inv.m, discrete_pdf.m, discrete_rnd.m, empirical_cdf.m, empirical_inv.m, empirical_pdf.m, empirical_rnd.m, expcdf.m, expinv.m, exppdf.m, exprnd.m, fcdf.m, finv.m, fpdf.m, frnd.m, gamcdf.m, gaminv.m, gampdf.m, gamrnd.m, geocdf.m, geoinv.m, geopdf.m, geornd.m, hygecdf.m, hygeinv.m, hygepdf.m, hygernd.m, kolmogorov_smirnov_cdf.m, laplace_cdf.m, laplace_inv.m, laplace_pdf.m, laplace_rnd.m, logistic_cdf.m, logistic_inv.m, logistic_pdf.m, logistic_rnd.m, logncdf.m, logninv.m, lognpdf.m, lognrnd.m, nbincdf.m, nbininv.m, nbinpdf.m, nbinrnd.m, normcdf.m, norminv.m, normpdf.m, normrnd.m, poisscdf.m, poissinv.m, poisspdf.m, poissrnd.m, stdnormal_cdf.m, stdnormal_inv.m, stdnormal_pdf.m, stdnormal_rnd.m, tcdf.m, tinv.m, tpdf.m, trnd.m, unidcdf.m, unidinv.m, unidpdf.m, unidrnd.m, unifcdf.m, unifinv.m, unifpdf.m, unifrnd.m, wblcdf.m, wblinv.m, wblpdf.m, wblrnd.m, kolmogorov_smirnov_test.m, kruskal_wallis_test.m, base2dec.m, bin2dec.m, blanks.m, cstrcat.m, deblank.m, dec2base.m, dec2bin.m, dec2hex.m, findstr.m, hex2dec.m, index.m, isletter.m, mat2str.m, rindex.m, str2num.m, strcat.m, strjust.m, strmatch.m, strsplit.m, strtok.m, strtrim.m, strtrunc.m, substr.m, validatestring.m, demo.m, example.m, fail.m, speed.m, addtodate.m, asctime.m, clock.m, ctime.m, date.m, datenum.m, datetick.m, datevec.m, eomday.m, etime.m, is_leap_year.m, now.m: Use Octave coding conventions in all m-file %!test blocks
author Rik <octave@nomad.inbox5.com>
date Mon, 13 Feb 2012 07:29:44 -0800
parents 11949c9795a0
children 86854d032a37
line wrap: on
line source

## Copyright (C) 2008-2012 David Bateman
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or (at
## your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING.  If not, see
## <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn  {Function File} {} datetick ()
## @deftypefnx {Function File} {} datetick (@var{form})
## @deftypefnx {Function File} {} datetick (@var{axis}, @var{form})
## @deftypefnx {Function File} {} datetick (@dots{}, "keeplimits")
## @deftypefnx {Function File} {} datetick (@dots{}, "keepticks")
## @deftypefnx {Function File} {} datetick (@dots{ax}, @dots{})
## Add date formatted tick labels to an axis.  The axis the apply the
## ticks to is determined by @var{axis} that can take the values "x",
## "y" or "z".  The default value is "x".  The formatting of the labels is
## determined by the variable @var{form}, that can either be a string in
## the format needed by @code{dateform}, or a positive integer that can
## be accepted by @code{datestr}.
## @seealso{datenum, datestr}
## @end deftypefn

function datetick (varargin)

  [h, varargin, nargin] = __plt_get_axis_arg__ ("datetick", varargin{:});

  oldh = gca ();
  unwind_protect
    axes (h);
    __datetick__ (varargin{:});
  unwind_protect_cleanup
    axes (oldh);
  end_unwind_protect

endfunction


%!demo
%! clf;
%! yr = 1900:10:2000;
%! pop = [76.094, 92.407, 106.461, 123.077 131.954, 151.868, 179.979, ...
%!        203.984, 227.225, 249.623, 282.224];
%! plot (datenum (yr, 1, 1), pop);
%! title ("US population (millions)");
%! xlabel ("Year");
%! datetick ("x", "YYYY");

%!demo
%! clf;
%! yr = 1988:2:2002;
%! yr = datenum (yr,1,1);
%! pr = [12.1 13.3 12.6 13.1 13.3 14.1 14.4 15.2];
%! plot (yr, pr);
%! xlabel ("year");
%! ylabel ("average price");
%! ax = gca;
%! set (ax, "xtick", datenum (1990:5:2005,1,1));
%! datetick (2, "keepticks");
%! set (ax, "ytick", 12:16);

## Remove from test statistics.  No real tests possible.
%!assert (1)

function __datetick__ (varargin)

  keeplimits = false;
  keepticks = false;
  idx = [];
  for i = 1 : nargin
    arg = varargin {i};
    if (ischar (arg))
      if (strcmpi (arg, "keeplimits"))
        keeplimits = true;
        idx = [idx, i];
      elseif (strcmpi (arg, "keepticks"))
        keepticks = true;
        idx = [idx, i];
      endif
    endif
  endfor

  varargin(idx) = [];
  nargin = length (varargin);
  form = [];
  ax = "x";

  if (nargin != 0)
    arg = varargin{1};
    if (ischar (arg) && (strcmp (arg, "x") || strcmp (arg, "y")
                         || strcmp (arg, "z")))
      ax = arg;
      if (nargin > 1)
        form = varargin{2};
        varargin(1:2) = [];
      else
        varargin(1) = [];
      endif
    else
      form = arg;
      varargin(1) = [];
    endif
  endif

  ## Don't publish the existence of this variable for use with dateaxis
  if (length (varargin) > 0)
    startdate = varargin{1};
  else
    startdate = [];
  endif

  if (! isempty (form))
    if (isnumeric (form))
      if (! isscalar (form) || floor (form) != form || form < 0)
        error ("datetick: expecting FORM argument to be a positive integer");
      endif
    elseif (! ischar (form))
      error ("datetick: expecting valid date format string");
    endif
  endif

  if (keepticks)
    ticks = get (gca (), strcat (ax, "tick"));
  else
    ## Need to do our own axis tick position calculation as
    ## year, etc, don't fallback on nice datenum values.
    objs = findall (gca());
    xmax = NaN;
    xmin = NaN;
    for i = 1 : length (objs)
      fld = get (objs (i));
      if (isfield (fld, strcat (ax, "data")))
        xdata = getfield (fld, strcat (ax, "data"))(:);
        xmin = min (xmin, min (xdata));
        xmax = max (xmax, max (xdata));
      endif
    endfor

    if (isnan (xmin) || isnan (xmax))
      xmin = 0;
      xmax = 1;
    elseif (xmin == xmax)
      xmax = xmin + 1;
    endif

    N = 3;
    if (xmax - xmin < N)
      ## Day scale or less
      if (xmax - xmin < N / 24 / 60 / 60)
        scl = 1 / 24 / 60 / 60;
      elseif (xmax - xmin < N / 24 / 6)
        scl = 1 / 24 / 60;
      else
        scl = 1 / 24;
      endif
      sep = __calc_tick_sep__ (xmin / scl , xmax / scl);
      xmin = sep * floor (xmin / scl / sep);
      xmax = sep * ceil (xmax / scl / sep);
      nticks = (xmax - xmin) / sep + 1;
      xmin *= scl;
      xmax *= scl;
    else
      [ymin, mmin, dmin] = datevec (xmin);
      [ymax, mmax, dmax] = datevec (xmax);
      minyear = ymin + (mmin - 1) / 12 + (dmin - 1) / 12 / 30;
      maxyear = ymax + (mmax - 1) / 12 + (dmax - 1) / 12 / 30;
      minmonth = mmin + (dmin - 1) / 30;
      maxmonth = (ymax  - ymin) * 12 + mmax + (dmax - 1) / 30;

      if (maxmonth - minmonth < N)
        sep = __calc_tick_sep__ (xmin, xmax);
        xmin = sep * floor (xmin / sep);
        xmax = sep * ceil (xmax / sep);
        nticks = (xmax - xmin) / sep + 1;
      elseif (maxyear - minyear < N)
        sep = __calc_tick_sep__ (minmonth , maxmonth);
        xmin = datenum (ymin, sep * floor (minmonth / sep), 1);
        xmax = datenum (ymin, sep * ceil (maxmonth / sep), 1);
        nticks = ceil (maxmonth / sep) - floor (minmonth / sep) + 1;
      else
        sep = __calc_tick_sep__ (minyear , maxyear);
        xmin = datenum (sep * floor (minyear / sep), 1, 1);
        xmax = datenum (sep * ceil (maxyear / sep), 1, 1);
        nticks = ceil (maxyear / sep) - floor (minyear / sep) + 1;
      endif
    endif
    ticks = xmin + [0 : nticks - 1] / (nticks - 1) * (xmax - xmin);
  endif

  if (isempty (form))
    r = max(ticks) - min(ticks);
    if r < 10/60/24
      ## minutes and seconds
      form = 13;
    elseif r < 2
      ## hours
      form = 15;
    elseif r < 15
      ## days
      form = 8;
    elseif r < 365
      ## FIXME -- FORM should be 19 for European users who use dd/mm
      ## instead of mm/dd.  How can that be determined automatically?
      ## months
      form = 6;
    elseif r < 90*12
      ## quarters
      form = 27;
    else
      ## years
      form = 10;
    endif
  endif

  if (length (ticks) == 6)
    ## Careful that its not treated as a datevec
    if (! isempty (startdate))
      sticks = strvcat (datestr (ticks(1:end-1) - ticks(1) + startdate, form),
      datestr (ticks(end) - ticks(1) + startdate, form));
    else
      sticks = strvcat (datestr (ticks(1:end-1), form),
      datestr (ticks(end), form));
    endif
  else
    if (! isempty (startdate))
      sticks = datestr (ticks - ticks(1) + startdate, form);
    else
      sticks = datestr (ticks, form);
    endif
  endif

  sticks = mat2cell (sticks, ones (rows (sticks), 1), columns (sticks));

  if (keepticks)
    if (keeplimits)
      set (gca(), strcat (ax, "ticklabel"), sticks);
    else
      set (gca(), strcat (ax, "ticklabel"), sticks, strcat (ax, "lim"),
      [min(ticks), max(ticks)]);
    endif
  else
    if (keeplimits)
      set (gca(), strcat (ax, "tick"), ticks, strcat (ax, "ticklabel"), sticks);
    else
      set (gca(), strcat (ax, "tick"), ticks, strcat (ax, "ticklabel"), sticks,
      strcat (ax, "lim"), [min(ticks), max(ticks)]);
    endif
  endif
endfunction

function [a, b] = __magform__ (x)
  if (x == 0)
    a = 0;
    b = 0;
  else
    l = log10 (abs (x));
    r = fmod (l, 1);
    a = 10 .^ r;
    b = fix (l - r);
    if (a < 1)
      a *= 10;
      b -= 1;
    endif
    if (x < 0)
      a = -a;
    endif
  endif
endfunction

## A translation from Tom Holoryd's python code at
## http://kurage.nimh.nih.gov/tomh/tics.py
function sep = __calc_tick_sep__ (lo, hi)
  persistent sqrt_2  = sqrt (2.0);
  persistent sqrt_10 = sqrt (10.0);
  persistent sqrt_50 = sqrt (50.0);

  ticint = 5;

  ## Reference: Lewart, C. R., "Algorithms SCALE1, SCALE2, and
  ## SCALE3 for Determination of Scales on Computer Generated
  ## Plots", Communications of the ACM, 10 (1973), 639-640.
  ## Also cited as ACM Algorithm 463.

  [a, b] = __magform__ ((hi - lo) / ticint);

  if (a < sqrt_2)
    x = 1;
  elseif (a < sqrt_10)
    x = 2;
  elseif (a < sqrt_50)
    x = 5;
  else
    x = 10;
  endif
  sep = x * 10 .^ b;
endfunction