来自“动态”数据JSON值的多折线图

时间:2018-11-01 23:40:53

标签: javascript d3.js

我是D3的新手,并尝试根据动态JSON值创建折线图。 我的JSON当前看起来像这样:

{
 "rows": [
  {
  "ts": "2018-10-29T23:45:00-04:00 New_York",
  "v0": "68.44398498535156 °F",
  "v1": "69.8637466430664 °F",
  "v2": "70.54344940185547 °F",
  "v3": "69.80231475830078 °F",
  "v4": "66.51739501953125 °F",
  "v5": "71.56026458740234 °F"
  },
  {
  "ts": "2018-10-30T00:00:00-04:00 New_York",
  "v0": "68.3259048461914 °F",
  "v1": "69.73896026611328 °F",
  "v2": "70.41132354736328 °F",
  "v3": "69.67794036865234 °F",
  "v4": "66.24201965332031 °F",
  "v5": "71.42134094238281 °F"
  }
 ]
}

我可以拥有尽可能少的一个。名称始终一致,始终以 v0 开头,并针对每个值进行迭代。我不知道如何开始遍历每个对象,并为每个 v 值绘制一条新线。

d3.json(removedJsonUri, function(error, d) {

    var data = d.rows;
    var keys = [];
    var lines = [];

    data.forEach((item) => {
        keys = Object.keys(item);
        Object.entries(item).forEach(([key, val]) => {
            if(key == "ts"){
                item[key] = new Date(item[key].replace('-04:00 New_York',''));
            } else {
               item[key] = item[key].replace('°F','');
            }
        });
    });

  if (error) throw error;

  var svg = d3.select("svg"),
      margin = {top: 20, right: 20, bottom: 30, left: 50},
      width = +svg.attr("width") - margin.left - margin.right,
      height = +svg.attr("height") - margin.top - margin.bottom,
      g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");



  var x = d3.scaleTime()
      .rangeRound([0, width]);

  var y = d3.scaleLinear()
      .rangeRound([height, 0]);

  keys.shift();

  for(var i = 0, length = keys.length; i < length; i++){
    var k = "line" + keys[i];
    window[k] = d3.line()
      .x(function(d) { return x(d.ts); })
      .y(function(d) { return y(d[keys[i]]); });


    lines.push(k);
      console.log(lines);
  }

  x.domain(d3.extent(data, function(d) { return d.ts; }));
  y.domain([0, d3.max(data, function(d) {
      return Math.max(d.v0, d.v1); })]);

  g.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x))
    .select(".domain")
      .remove();

  g.append("g")
      .call(d3.axisLeft(y))
    .append("text")
      .attr("fill", "#000")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", "0.71em")
      .attr("text-anchor", "end")
      .text("Temp (°F)");

  for(var o = 0, length = lines.length; o < length; o++){  

    g.append("path")
        .datum(data)
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("stroke-width", 1.5)
        .attr("d", lines[o]);
  }

});

这是我走了多远,对我来说很有意义,但不会画线。我看到的每个地方都使用一致的值名称。我知道我很容易错过一些事情,只是卡住了。

谢谢

0 个答案:

没有答案