简体   繁体   中英

How can I update a bar chart in d3.js?

I'm trying to update a d3.js bar chart whenever a user clicks a button.

I've been tying to add in a transition somewhere as show here but it doesn't update my data on the fly.

I'm working with this jsfiddle .

I've tried something like the following code but it doesn't update my data:

btn.onclick = function(){
  data.push({date: new Date(2013, 3, 10), total: 78});
  updatePlot();
}

function updatePlot(){
  d3.select('#graphTest').transition();
}

How can I change my updatePlot method so that it updates the data in my bar graph?

It looks like you're skipping a few steps. D3 doesn't actually do a ton of magic for you behind the scenes. You still need to push the data around and update the DOM yourself. D3 just provides a convenient programming model for managing this process.

So, with any visualization you've got the following interesting pieces:

  1. Data array
  2. DOM nodes
  3. Data array elements bound to DOM nodes.
  4. Attributes and styles on DOM nodes.

Your code is updating the data array but it's not managing any of the other parts. You need to drive your updated data back in to the DOM (and specifically the attributes/styles that make the nodes visible).

So update plot will need to do the following:

  1. Call selection.data to bind the new data to the existing DOM. You can defined a key function to control how data maps to DOM nodes.
  2. Handle the enter , exit and update selections however you like.
  3. Transition the attributes and styles based on the new data.

For #3, this isn't just a matter of calling selection.transition , but instead you need to think about which attributes and styles you wish to transition. Calling attr and style on a transition is exactly like calling them on a selection, except the DOM gets updated many times with interpolated values instead of just once with the final value.

To understand this process better you should read Thinking with Joins and Working with Transitions .

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