简体   繁体   中英

Update D3 pie chart with JSON

I have this pie chart : 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.

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 :

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. I have seen this example : 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:

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 . You should add path.enter().append(... to that function for when your data grows.

Updated fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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