d3.js How to add lines to a bar chart

后端 未结 2 786
情深已故
情深已故 2020-12-15 01:40

I have a data set of 4 values. [a,b,c,d]. Currently they are displayed in a bar chart, for each value one bar. Now as values c and d are averages, i would like to display th

2条回答
  •  轮回少年
    2020-12-15 01:44

    Make a list of objects with two properties out of your data:

    var data = [1,2,3,4];
    var objects = data.slice(0, data.length/2).map(
      function(d,i) { return { value:d, average:data[i+data.length/2] }; } 
    );
    

    Then you can do something like this (not tested):

    var bars = chart.selectAll("g.bar")
       .data(objects)
      .enter().append("g")
        .attr("class", "bar")
        .attr("transform", function(d,i) { return "translate("+(i*10)+",0)"; });
    
    
    bars.append("rect")
        .attr("x", 0)
        .attr("y", function(d,i) { return height - d.value; })
        .attr("width", 10)
        .attr("height", function(d,i) { return d.value; });
    
    bars.append("line")
        .attr("x1", 0)
        .attr("y1", function(d,i) { return height - d.average; })
        .attr("x2", 10)
        .attr("y2", function(d,i) { return height - d.average; });
    

提交回复
热议问题