monthendAxis.html 2.37 KB
Newer Older
afe's avatar
afe committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
<!DOCTYPE html>
<meta charset="utf-8">
<link href="../src/nv.d3.css" rel="stylesheet" type="text/css">
<style>

</style>

<body>


  <script src="../lib/d3.v2.js"></script>
  <script src="../nv.d3.js"></script>
  <script>

    function ilog(text) {
      console.log(text);
      return text;
    }


  function daysInMonth(month,year) {
    var m = [31,28,31,30,31,30,31,31,30,31,30,31];
    if (month != 2) return m[month - 1];
    if (year%4 != 0) return m[1];
    if (year%100 == 0 && year%400 != 0) return m[1];
    return m[1] + 1;
  }


  function d3_time_range(floor, step, number) {
    return function(t0, t1, dt) {
      var time = floor(t0), times = [];
      if (time < t0) step(time);
      if (dt > 1) {
        while (time < t1) {
          var date = new Date(+time);
          if (!(number(date) % dt)) times.push(date);
          step(time);
        }
      } else {
        while (time < t1) times.push(new Date(+time)), step(time);
      }
      return times;
    };
  }


  d3.time.monthEnd = function(date) {
    return new Date(date.getFullYear(), date.getMonth(), 0);
  };


  d3.time.monthEnds = d3_time_range(d3.time.monthEnd, function(date) {
      date.setUTCDate(date.getUTCDate() + 1);
      date.setDate(daysInMonth(date.getMonth() + 1, date.getFullYear()));
    }, function(date) {
      return date.getMonth();
    }
  );




  var margin = {top: 10, right: 40, bottom: 40, left: 40},
      width = 960 - margin.left - margin.right,
      height = 80 - margin.top - margin.bottom;

  var x = d3.time.scale()
      .domain([new Date(2010, 0, 1), new Date(2011, 0, 1)])
      .range([0, width]);

  var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom")
      //.ticks(d3.time.months)
      .ticks(d3.time.monthEnds)
      //.tickSubdivide(3)
      .tickSize(8, 4, 0)
      .tickFormat(d3.time.format("%x"));
      //.tickFormat(d3.time.format("%B"));

  var svg = d3.select("body").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)

    .selectAll("text")
      .attr("text-anchor", "middle")
      //.attr("text-anchor", "start")
      .attr("x", 0)
      .attr("y", 12);

  </script>