label coordinate axis with 1-2-5-ticks for given numeric range

半腔热情 提交于 2020-05-15 21:20:53

问题


The somewhat unclear question Exponential Graph Animation P5js Canvas contains an interesting detail about programmatically labeling axes for a broad variety of ranges. I instantly remembered that gnuplot does what I searched for. By interactively zooming in the preview window (and without any particular ticks specification), I observed that it automatically selects a labeling scheme with an amount of between 4 and 10 ticks and a fixed distance of 1, 2, or 5 times some power of 10.

The following 4 examples can be taken as snapshots of this interactive process.

gnuplot> set xrange [0:1]
gnuplot> set yrange [0:exp(1)]
gnuplot> plot exp(x)

gnuplot> set xrange [0:2]
gnuplot> set yrange [0:exp(2)]
gnuplot> plot exp(x)

gnuplot> set yrange [0:exp(5)]
gnuplot> set xrange [0:5]
gnuplot> plot exp(x)

gnuplot> set yrange [0:exp(10)]
gnuplot> set xrange [0:10]
gnuplot> plot exp(x)

To implement such a labeling scheme, how do I find the ideal 1-2-5-tick distance for a given range?
(in pseudo code or some usual language like JavaScript or Python)


回答1:


To get one of these 1-2-5-tick schemes from a range (0..max), we have to separate order of magnitude (exponent) and digits (mantissa), and to find the most appropriate digit (1, 2, or 5) below or equal to the most significant digit of a representative.

See such a function in JavaScript:

// find 1-2-5-tick distance for a given range
function tick_distance(range) {
  let find_factor = function(v) {
    if (v >= 5) {
      v = 5;
    } else if (v >= 2) {
      v = 2;
    } else if (v >= 1) {
      v = 1;
    }
    return v;
  };

  let representative = range * 0.24
  let l10 = Math.log10(representative);
  let exponent = Math.floor(l10);
  let mantissa = l10-exponent;
  let realdist = Math.pow(10, mantissa);
  let factor = find_factor(realdist);
  let dist = factor * Math.pow(10, exponent);
  return dist;
}

The heuristic factor of 0.24 for the representative gives tick counts between 4 and 10 over changing orders of magnitude; 0.23 would also work whereas 0.25 provides the maximum of 10 ticks only for ranges of 2*10^n.

  • 0.22 gives sometimes 11 ticks
  • 2.26 gives sometimes 3 ticks

I admit that I'm myself am interested in the "exact value" for this factor.



来源:https://stackoverflow.com/questions/61502601/label-coordinate-axis-with-1-2-5-ticks-for-given-numeric-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!