繁体   English   中英

甜甜圈图d3.js

[英]Donut chart d3.js

我尝试修改示例。 我想创建两个数据数组,并使用特殊的mergingAr()函数而不是data.csv合并它们。 但这行不通。 有一个没有任何数据的彩色图表。 我无法在代码中找到问题所在。 因此,这里是:

var width = 250,
    height = 250,
    radius = 230;

var arr1 = [44, 64]; //age
var arr2 = [14106543, 8819342]; //population

function type(d) {
  d[1] = +d[1];
  return d;
}

function mergingAr(array1, array2)
{

    var i, out = [];
    for(i=0;i<array1.length;i++)
    {
        out.push([array1[i],array2[i]]);
    }
        return out;
   }

var data = mergingAr(arr1, arr2);

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

var arc = d3.svg.arc()
    .outerRadius(radius - 100)
    .innerRadius(radius - 180);

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

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

  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(d[0]); });

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


      var legend = svg.selectAll(".legend")
      .data(color.domain())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; });

谢谢大家的帮助!

您的数据在那里,但是颜色错误。 现在,您可以使用以下行设置路径颜色:

.style("fill", function(d) { return color(d[0]); });

问题在于您的数据是对象,而不是数组。 (它由pie函数转换),因此您需要引用对象上的data属性,然后获取该数组的零索引,如下所示:

.style("fill", function(d) { return color(d.data[0]); });

暂无
暂无

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

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