绘制D3中的日期和时间

时间:2016-02-18 06:48:31

标签: javascript d3.js plot

我正在尝试绘制从气象站获取的时间读数。每天应该有24个读数。因此,这里的目标是绘制x轴上的日(MMM dd)和y轴上的时间(HH:mm)。

我开始使用unix时间戳,我最不知道如何将日期与绘图时间分开。我认为在解析中这样做,然后绘制两个可以工作,但没有。

var formatTime = d3.time.format("%H:%M")
    formatDate = d3.time.format("%b %e")

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

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 + ")");


d3.json("http://www.microveggies.com/data/get/all/all/range/2015-01-01/2016-02-17", function(error, data) {
  if (error) throw error;

  data.forEach(function(d) {
    d.time = formatTime(new Date(d.timestamp * 1000));
    d.date = formatDate(new Date(d.timestamp * 1000));
    d.external_temp = +d.external_temp;
  });

  // Set the ranges
  var x = d3.time.scale().range([0, width]);
  var y = d3.time.scale().range([height, 0]);

  // Scale the range of the data
  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain(d3.extent(data, function(d) { return d.time; }));

  var xAxis = d3.svg.axis()
    .scale(x)
    .orient('bottom')
    .ticks(d3.time.days, 1)
    .tickSize(0)
    .tickPadding(8);

  var yAxis = d3.svg.axis()
    .scale(y)
    .orient('left')
    .ticks(d3.time.minutes, 30)
    .tickSize(0)
    .tickPadding(8);

    // Add the scatterplot
    svg.selectAll("dot")
        .data(data)
      .enter().append("circle")
        .attr("r", 3.5)
        .attr("cx", function(d) { return d.date; })
        .attr("cy", function(d) { return d.time; });

    // Add the X Axis
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    // Add the Y Axis
    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

});
body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.dot {
  stroke: #000;
}

svg {
  margin: 0 auto;
}
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<body>

2 个答案:

答案 0 :(得分:1)

Here is a fiddle

enter image description here

<!DOCTYPE html>
<meta charset="utf-8">
<style>
  .chart {
    font-family: Arial, sans-serif;
    font-size: 10px;
  }

  .axis path,
  .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }
</style>

<body>

  <!-- load the d3.js library -->
  <script src="./d3.min.js"></script>

  <script>
    var margin = {
        top: 40,
        right: 40,
        bottom: 40,
        left: 40
      },
      width = 600,
      height = 400;

    var formatTime = d3.time.format("%H:%M:00")
    formatDate = d3.time.format("%Y-%m-%d");

    d3.json("http://www.microveggies.com/data/get/all/all/range/2015-01-01/2016-02-17", function (error, data) {
      if (error) throw error;
      data.forEach(function (d) {
        d.time = formatTime(new Date(d.timestamp * 1000));
        d.date = formatDate(new Date(d.timestamp * 1000));
        d.external_temp = +d.external_temp;
      });
      console.log(JSON.stringify(data));

      var x = d3.time.scale()
        .domain([d3.time.day.offset(new Date(data[data.length - 1].date), 0), new Date(data[0].date)])
        .rangeRound([0, width - margin.left - margin.right]);

      var y = d3.scale.linear()
        .domain([0, d3.max(data, function (d) {
          return 24;
        })])
        .range([height - margin.top - margin.bottom, 0]);

      var xAxis = d3.svg.axis()
        .scale(x)
        .orient('bottom')
        .ticks(d3.time.days, 1)
        .tickFormat(d3.time.format('%d-%m-%Y'))
        .tickSize(0)
        .tickPadding(8);

      var yAxis = d3.svg.axis()
        .scale(y)
        .orient('left')
        .tickPadding(8);

      var svg = d3.select('body').append('svg')
        .attr('class', 'chart')
        .attr('width', width)
        .attr('height', height)
        .append('g')
        .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');

      svg.selectAll('.chart')
        .data(data)
        .enter().append('circle')
        .attr('cx', function (d) {
          return x(new Date(d.date));
        })
        .attr('cy', function (d) {
          return height - 80 - (new Date("2015-01-01 " + d.time).getHours() * (height - 80) / 24);
        })
        .attr('r', function (d) {
          return (d.external_temp + 3) / 10;
        });

      svg.append('g')
        .attr('class', 'x axis')
        .attr('transform', 'translate(0, ' + (height - margin.top - margin.bottom) + ')')
        .call(xAxis)
        .selectAll("text")
        .attr("transform", "rotate(40)")
        .style("text-anchor", "start");

      svg.append('g')
        .attr('class', 'y axis')
        .call(yAxis);

    });
  </script>
</body>

答案 1 :(得分:0)

所以这个问题与d3.js无关,它是关于在js中处理时间戳的形式,对吧?我建议看看momentjs,这使得处理日期和时间变得非常舒适。