Skip to content Skip to sidebar Skip to footer

D3 Chart Not Updating Properly

I'm creating a stacked bar chart. I created a data object using d3.stack, which I bind to the 'g' element to handle the proper fill. Then I want to access the lower levels of the d

Solution 1:

Let's break down your code:

1.Append a new g with class invalid-group:

   invalid_svg.append('g')
      .attr('class', 'invalid-group')

2.Perform a join with a new data array to enter new child g elements:

   .selectAll('g')
    .data(stackedData)
    .join(...

3.Select the first element with class invalid-group and select each child g:

  d3.select('.invalid-group').selectAll('g')

4.Perform a data join with the bound data of each child g of the first element with class invalid-group:

 .selectAll('rect')
        .data(d=> d)
        .join(

Because step 1 appends a new g each iteration, step 2 only ever enters elements: there are no child elements in the newly appended g to update. New data is only ever appended to these new g elements.

On every iteration other than the first, step 3 ignores these newly joined/entered child g elements because it only selects those appended in the first iteration (d3.select('.invalid-group') returns the first matching element - which is the g appended on the first iteration), and finally step 4 re-binds the data that was originally bound to the children of the g appended in step one on the first iteration. This data is never updated, so the rectangles never get new bound datums.

Assuming this code is in an update function, remove the invalid_svg.append('g') in step one and do this appending once outside of the update function. Either re-select it to conduct the join in step 2 or use a variable to hold it.

Post a Comment for "D3 Chart Not Updating Properly"