1
votes

After making several bar charts using enter, update, exit method in D3js, I wanted to try the same with a pie chart. I thought I applied selections correctly, but the pie chart won't update with the new data in JSON. I looked for similar examples online, but couldn't find one which involved an .on("click" method. I want users to compare the lifespans of humans and animals using a donut chart. I'm trying to implement the search tool through the database of animals right now.

here's what a data object looks like for the query Goat:

[{"Animal":"Male","Life_Span":73},{"Animal":"Goat","Life_Span":10}]

I'm having trouble with this code in particular:

var pie = d3.pie()
    .sort(null)
    .value(function(d) { return d.Life_Span; });
//code for accessing data, etc
//enter remove selections
  var path = svg.selectAll("path")
      .data(pie(newdata))
  var enterdata = 
      path.enter().append("path")
      .attr("d",arc)

  path.exit().remove()
  enterdata.exit().remove()

I posted the full code on Plunkr here: http://plnkr.co/edit/3QSAPxQpju63tIXRd9p7?p=preview

A few weeks into learning d3js, I'm still struggling with enter,update exit selections even after reading many tutorials on the subject. I would really appreciate any help. Thanks

1

1 Answers

3
votes

In D3 v4.x, you need to merge the update and enter selections:

var enterdata = path.enter()
    .append("path")
    .merge(path)
    .attr("d",arc)

You don't need an exit selection because your data array has always 2 objects: except for the first time, your enter selection is always 0, and your exit selection is always 0.

I took the liberty of colouring the paths in different colours, according to their indices:

.attr("fill", (d,i) => i ? "teal" : "brown");

Here is your updated plunker: http://plnkr.co/edit/l6OzmxVfid9Cj7iv7IMg?p=preview

PS: You have some problems in your code, which I'll not change (here I'm only answering your main question), but I reckon you should think about them:

  1. Don't mix jQuery and D3. You can do everything here without jQuery
  2. Don't load all your CSV every time the user chooses an animal. It doesn't make sense. Instead of that, put the click function inside the d3.csv function (that way, you load the CSV only once).