Using nested data with D3.js

前端 未结 1 1249
失恋的感觉
失恋的感觉 2021-01-21 02:24

I am trying to display a beautiful line graph using D3. The problem I have is with the format of the data.

I have the following data (as an example):

var         


        
相关标签:
1条回答
  • 2021-01-21 02:55

    There’s a few problems here.

    First, you’re appending an svg:path element to an svg:text element. It seems to me like you’re trying to create an svg:g element with the class "rule", but your code defines the selection rules as a set of svg:text elements. Create the svg:g elements first, and then append svg:text elements:

    var rules = vis.selectAll("g.rule")
        .data(data)
      .enter().append("svg:g")
        .attr("class", "rule");
    
    rules.append("svg:text")
        …
    

    The second problem is that the data operator is evaluated once per group, rather than once per element. See the section "Operating on Selections" in the API reference for more details. You have one svg:svg element in vis, so you have one group in rules, and so your data function is only called once:

    function(d, i) {
      return d.data;
    }
    

    Then, the resulting data elements are mapped to the rules selection… which already have defined data from the previous selectAll and append when they were created.

    The simple fix is to use the map operator rather than the data operator, which is evaluated once per element rather than once per group.

    rules.append("svg:path")
        .map(function(d) { return d.data; })
        .attr("d", d3.svg.line()
        …
    

    Alternatively, you could pass the data directly to the line generator, but that requires you declaring the line generator ahead of time rather than inlining it:

    var line = d3.svg.line()
        .x(function(d) { return x(d[0]); })
        .y(function(d) { return y(d[1]); });
    
    rules.append("svg:path")
        .attr("d", function(d) { return line(d.data); })
        …
    

    Hope this helped!

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