d3 JSON multiple line chart

后端 未结 2 469
不知归路
不知归路 2021-01-01 06:37

I\'m trying to make a plot with multiple lines on it from a JSON blob that looks like:

{\"2007\": [{\"val\":10, \"mon\":10}, {\"val\":20, \"mon\":11}, {\"va         


        
相关标签:
2条回答
  • 2021-01-01 07:13

    My guess is that the biggest problem here is that you're starting with an object, not an array. d3.data takes an array, not an object, so you might need your data set up like:

    [
      [{"val":10, "mon":10}, {"val":20, "mon":11}, {"val":40, "mon":12}, ...],
      [{"val":20, "mon":8}, {"val":20, "mon":9}, {"val":40, "mon":10}, ...],
      ...
    ]
    

    If you need to convert your current data to this format, look at d3.entries, which will give you an array with your key as well as your array of points:

    [
      {
        key: "2008",
        value: [{"val":10, "mon":10}, {"val":20, "mon":11}, {"val":40, "mon":12}, ...]
      },
      { 
        key: "2008",
        value: [{"val":20, "mon":8}, {"val":20, "mon":9}, {"val":40, "mon":10}, ...]
      },
      ...
    ]
    

    See this fiddle for a simple-case version of your graph, using the first data format above: http://jsfiddle.net/nrabinowitz/kmmyc/

    0 讨论(0)
  • 2021-01-01 07:14

    Here's what worked out in case anyone else runs across this problem. The trick is to pass a function that returns the values in the associative array in the "d" attribute of the path element.

      entries = d3.entries(data);
    
      var colors = d3.scale.category20()
        .domain(d3.keys(data));
    
      var line = d3.svg.line()
        .interpolate("basis")
        .x(function(d) { return x(d.month) })
        .y(function(d) { return y(d.value) });
    
      svg1.selectAll(".line")
        .data(entries)
      .enter().append("path")
        .attr("class", "line")
        // function(d), not just line function 
        .attr("d", function(d){ return  line(d.value); })
        .attr("stroke", function(d) { return colors(d.key) });
    

    Some help from this answer too: Using nested data with javascript D3 problem

    0 讨论(0)
提交回复
热议问题