Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

dynamic - How to update d3.js bar chart with new data

I’ve started with the “Let’s make a bar chart I” example here: http://bost.ocks.org/mike/bar/

And I’m having a hard time figuring out how to make the very simple bar chart made with HTML5 elements update with new data. Here is my code:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #work_queues_chart div {
        font-size: 0.5em;
        font-family: sans-serif;

        color: white;
        background-color: steelblue;

        text-align: right;
        padding: 0.5em;
        margin: 0.2em;
      }
    </style>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8" />
    <script type="text/javascript">

      function init() {

        var data = [0, 0, 0, 0, 0, 0];

        /* scale is a function that normalizes a value in data into the range 0-98 */
        var scale = d3.scale.linear()
                      .domain([0, 200])
                      .range([0, 98]);

        var bars = d3.select("#work_queues_chart")
                     .selectAll("div")
                       .data(data)
                     .enter().append("div");

        bars.style("width", function(d) { return scale(d) + "%"; })
        bars.text(function(d) { return d; });

      }

      function update() {

        var data = [4, 8, 15, 16, 23, 42];

        /* http://stackoverflow.com/questions/14958825/dynamically-update-chart-data-in-d3 */
      }

      window.onload = init;

    </script>

  </head>
  <body>
    <div id="work_queues_chart" />
    <button onclick="update()">Update</button>
  </body>
</html>

The question is what do I put into update() to cause the bars to draw with the new data? I tried d3.select("#work_queues_chart").selectAll("div").data(data) with the new data, but I’m unclear on what needs to happen next (or whether that was the right move).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have create a fiddle for you here. It is a simple take on what you had with a few changes, particularly separating the enter, update and exit selections. This should help you start understanding the update process in D3.

// enter selection
bars
    .enter().append("div");

// update selection
bars
    .style("width", function (d) {return scale(d) + "%";})
    .text(function (d) {return d;});

// exit selection
bars
    .exit().remove();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...