简体   繁体   English

使用JSON更新D3饼图

[英]Update D3 pie chart with JSON

I have this pie chart : http://jsfiddle.net/fg9MU/265/ 我有这个饼图: http : //jsfiddle.net/fg9MU/265/

It doesn't seem to like it when I change from a dataset of length 3, to one of length 2. 当我从长度为3的数据集更改为长度为2的数据集时,似乎并不喜欢它。

Original data: 原始数据:

var dataSet1 = [{
  "id": "001 Helicopter",
  "name": "Helicopter",
  "priority": "highClass",
  "value": 1
}, {
  "id": "005 Rear Rotor",
  "name": "Rear Rotor",
  "priority": "lowClass",
  "value": 1
}, {
  "id": "002 Rotor",
  "name": "Rotor",
  "priority": "lowClass",
  "value": 1
}]

Change dataset : 变更资料集:

function changeData(data) {
    path.data(pie(data));
    path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs

  }

Pass the function new data : 传递函数新数据:

changeData(dataSet2);

Dataset2 : 数据集2:

var dataSet2 = [{
  "id": "001 Helicopter",
  "name": "Helicopter",
  "priority": "highClass",
  "value": 1
}, {
  "id": "004 Seat",
  "name": "Seat",
  "priority": "lowClass",
  "value": 1
}]

It doesn't seem to update the datasets. 它似乎没有更新数据集。 The one that's in both ie 'Helicopter' adjusts fine (1/2 of the chart) but the others don't. 两者中的一个(即“直升机”)可以很好地调整(图表的1/2),而其他两个则不能。 I have seen this example : http://bl.ocks.org/mbostock/5681842 我已经看到了以下示例: http : //bl.ocks.org/mbostock/5681842

It says to use this : 它说使用这个:

function type(d) {
  d.apples = +d.apples || 0;
  d.oranges = +d.oranges || 0;
  return d;
}

But I have no idea how to implement this into my dataset :( Any ideas ? 但是我不知道如何将其实现到我的数据集中:(任何想法?

You aren't handling the enter , update , exit pattern in your update function: 您没有在update函数中处理enterupdateexit模式:

function changeData(data) {
    var path = svg.datum(data)
      .selectAll("path").data(pie); //<-- update selection
    path.exit().remove(); //<-- exit selectin
    path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs for the paths left
  }

Note , even with this code change, you aren't handling entered items on changeData . 请注意 ,即使更改了此代码,您也不会处理changeData上输入的项目。 You should add path.enter().append(... to that function for when your data grows. 您应该在数据增长时将path.enter().append(...到该函数中。

Updated fiddle . 更新小提琴

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

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