甜甜圈图d3.js

Donut chart d3.js

本文关键字:js d3 甜甜圈      更新时间:2023-09-26

我试着修改这个例子。我想创建两个数据数组,并使用特殊的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; });

谢谢大家的帮助!

你的数据在那里,但你的颜色是错误的。现在,你有这样的行设置路径color:

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

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

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