D3.Js:无法创建Arc以使用数据集创建多个甜甜圈

时间:2019-10-30 15:02:58

标签: reactjs d3.js charts c3.js data-driven

我想使用d3 v4创建多个甜甜圈图。enter image description here

但出现错误:

  

d3.min.js:2错误:属性d:预期的moveto路径命令(“ M”或“ m”),“函数t(){var…

请参考来自jsfiddle的代码

var dataset = {
      "fir": [1, 2, 3, 4,2, 3, 1],
       "cloud": [1513606, 40000, 30000, 50600]
    };
var innerRadius = [100, 50];
    var outerRadius = [150, 100];

var width = 960,
    height = 500,
    radius = height / 2 - 10;

var arc = d3.arc();

var pie = d3.pie();

    var allColors = ['#DF3054', '#FF8E00', '#FFBD1D', '#EBE2B2', '#7DC3E6', '#7DC3E6', '#008CC8', '#00508E', '#8E26C9', '#E5E6ED', '#777980', '#F8E71C'];
    var color = d3.scaleOrdinal(allColors);

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

var gs = svg.selectAll("g").data(d3.values(dataset)).enter().append("g");
gs.selectAll("path")
    .data (
    function(d) {
      return pie(d);
    })
  .enter().append("path")
    .style("fill", function(d, i) { return color(i); })
    .attr("d", function(d, i, j) { return arc.innerRadius(innerRadius[j]).outerRadius(outerRadius[j]); });

1 个答案:

答案 0 :(得分:0)

代码有一些错误。

  1. 整个数据数组都需要传递给pie函数,以便可以计算角度:

    var arcs = pie(dataset.fir)

  2. 弧函数需要先设置半径,然后在路径生成器中调用该函数

    var arc = d3.arc()       .innerRadius(50)       .outerRadius(Math.min(width,height)/ 2-1)

...

.append(“路径”) .attr(“ d”,arc);

var data = [1, 1, 2, 3, 5, 8, 13, 21];


var dataset = {
      "fir": [1, 2, 3, 4, 2, 3, 1],
       "cloud": [1513606, 40000, 30000, 50600]
    };
var innerRadius = [100, 50];
var outerRadius = [150, 100];

var width = 960,
    height = 500,
    radius = height / 2 - 10;

var arc = d3.arc()
  .innerRadius(50)
  .outerRadius(Math.min(width, height) / 2 - 1)

var pie = d3.pie();

var arcs = pie(dataset.fir)

var allColors = ['#DF3054', '#FF8E00', '#FFBD1D', '#EBE2B2', '#7DC3E6', '#7DC3E6', '#008CC8', '#00508E',
      /* other colors */ '#8E26C9', '#E5E6ED', '#777980', '#F8E71C'];
var color = d3.scaleOrdinal()
	.range(allColors);

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

var gs = svg.selectAll("g")
  .data(arcs)
  .enter()
  .append("g")
  .append("path")
  .style("fill", function(d, i) { return color(i); })
  .attr("d", arc);
body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: auto;
  position: relative;
  width: 960px;
}

text {
  font: 10px sans-serif;
}

form {
  position: absolute;
  right: 10px;
  top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>