简体   繁体   English

如何使用Javascript在D3中使用forEach

[英]How to use forEach in d3 using Javascript

I'm trying to make a pie chart using d3. 我正在尝试使用d3制作饼图。 To do this I am send my data in a JSON format to my view and then I'd like to try and total up three of the parameters and then use these in the pie chart. 为此,我将数据以JSON格式发送到视图中,然后尝试合计三个参数,然后在饼图中使用它们。 So far I have managed to get the data to the view but now I need to use a foreach to total up the parameters. 到目前为止,我已经设法将数据显示到视图中,但是现在我需要使用一个foreach来汇总参数。 I'm only working on one at the moment. 我目前只在做一个。

Script: 脚本:

   var width = 960,
    height = 500,
    radius = Math.min(width, height) / 2;

        var color = d3.scale.ordinal()
            .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c"]);

        var arc = d3.svg.arc()
            .outerRadius(radius - 10)
            .innerRadius(0);

        var pie = d3.layout.pie()
            .sort(null)
            .value(function (d) { return d.Query; });

        var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height)
          .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

        var data = @Html.Raw(@Model.output);

        var QueryTotal = data.forEach(function(d) {
            d.Query = +d.Query;
        });

        console.log(QueryTotal);

            var g = svg.selectAll(".arc")
                .data(pie(data))
              .enter().append("g")
                .attr("class", "arc");

            g.append("path")
                .attr("d", arc)
                .style("fill", function (d) { return color("Query"); });

            g.append("text")
                .attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; })
                .attr("dy", ".35em")
                .style("text-anchor", "middle")
            .text(function (d) { return "Query"; });

How do I use a for each to total up the values, I've given it an attempt which you can see above. 我如何使用a来总计值,我已经尝试过了,您可以在上面看到。 It just returns undefined. 它只是返回未定义。

To sum the values, use reduce() 要对这些值求和,请使用reduce()

var QueryTotal = data.reduce(function(prev, d) {
    return prev + d.Query;
}, 0);

Or, using your existing structure: 或者,使用您现有的结构:

var QueryTotal = 0;

data.forEach(function(d) {
    QueryTotal += d.Query;
});

D3的方法是使用d3.sum()

var QueryTotal = d3.sum(data, function(d) { return d.Query; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM