简体   繁体   English

堆积的条形图更新不起作用d3.js

[英]Stacked bar chart update not working d3.js

I have a stacked bar chart here not cooperating. 我的堆叠条形图在这里不配合。 For some reason. 由于某些原因。 The part where I have my code update is not working. 我进行代码更新的部分无法正常工作。 At this point the code seems fine but I am just not able to get the transition to occur Anyone know how to do this? 在这一点上,代码看起来还不错,但我只是无法过渡到任何人都知道该怎么做? Thanks! 谢谢!

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>US2016</title>
    <!-- d3 and plugins -->
    <script src="http://d3js.org/d3.v3.js"></script>
    <!-- custom css -->
    <style type="text/css">
      body {
        font: 10px sans-serif;
      }
    </style>
  </head>
  <body>

  <h2>Random</h4>
  <div id="stacked-rep"></div>

  <script>

  var repColors = ['#403153','#9e7742','#0084ab','#e30513'];
  var repColorsLight = ['#e5dae7','#deba96','#c5d7e9','#f6b89f'];
  var repCandidates = ["Trump", "Cruz", "Rubio", "Kasich"];
  var carnival_colors = ["blue", "lightblue"];
    //Width and height
    var m = {top: 10, right: 10, bottom: 10, left: 10}, // margins
        h = 150 - m.left - m.right, // height
        w = 960 - m.top - m.bottom; // width
    //Create SVG element
    var svg = d3.select("#stacked-rep")
        .append("svg")
        .attr("width", w)
        .attr("height", h);

  function cumulChart(id, dataset) {
      // Set up stack method
      var stack = d3.layout.stack();
      //Data, stacked
      stack(dataset);

      // Set up scales
      var xScale = d3.scale.ordinal()
        .domain(d3.range(dataset[0].length))
        .rangeRoundBands([0, h], 0.2); // This is actually the Y scale (candidates)
      var yScale = d3.scale.linear()
        .domain([0, 
          d3.sum(dataset, function(d) {return d[0].y;})*1.2
          ])
        .range([0, w]); // This is actually the X Scale (States)

      // Add a group for each row of data
      var groups = svg.selectAll("g")
        .data(dataset)
        .enter()
        .append("g")
        .classed("g_stacked elements", true)
        // .attr("class", "g_stacked elements")
        .attr("transform", "translate(" + m.left + ",0)");

      // Add a rect for each data value
      var rects = groups
        .selectAll("rect")
        .data(function(d) { return d; });

      rects.enter()
        .append("rect")
        .attr("class", "stacked")
        .attr("stacked_state", function(d) { return "st"+ d.state; })
        .attr("x", function(d) {
          return yScale(d.y0);
        })
        .attr("y", function(d, i) {
          return xScale(i);
        })
        .attr("width", function(d) {
          return yScale(d.y);
        })
        .attr("height", xScale.rangeBand())
        .style("fill", function(d, i) {
          if (d.state == 19){
            return carnival_colors[1];
          }
          else {
            return carnival_colors[0];
          }
        })
        .style("stroke", function(d, i) {
          if (d.state == 19){
            return d3.rgb(carnival_colors[1]).darker() ;
          }
          else {
            return d3.rgb(carnival_colors[0]).darker() ;
          }
        })
        /*.on("mouseover", function(d) {
          console.log(d.state);
        })*/;

        // transition
        rects.transition() // this is to create animations
          .duration(500) // 500 millisecond
          .ease("bounce")
          .delay(500)
          // .attr("class", "stacked")
          // .attr("stacked_state", function(d) { return "st"+ d.state; })
          .attr("x", function(d) {
            return yScale(d.y0);
          })
          .attr("y", function(d, i) {
            return xScale(i);
          })
          .attr("width", function(d) {
            return yScale(d.y);
          })
          .attr("height", xScale.rangeBand());

  };

  var data = [
            [{
              "state": 19,
              "x": "Trump1",
              "y": 2000
            }],
            [{
              "state": 33,
              "x": "Trump2",
              "y": 3000
            }]
        ];


  cumulChart("#stacked-rep", data);

  // create a function to randomize things
  function rand_it(x){
   return Math.floor((Math.random() * x) + 1);
  };

  setInterval(function(){
    var object = [
            [{
              "state": 19,
              "x": "Trump1",
              "y": rand_it(20)
            }],
            [{
              "state": 33,
              "x": "Trump2",
              "y": rand_it(20)
            }]
        ];

    cumulChart("#stacked-rep", object);
    console.log(object[0][0].y,"---",object[1][0].y);
  }, 3000);

</script>
</body>
</html>

Just figured it out. 只是想通了。 The data part was not updating in the function. 数据部分未在函数中更新。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>US2016</title>
    <!-- d3 and plugins -->
    <script src="http://d3js.org/d3.v3.js"></script>
    <!-- custom css -->
    <style type="text/css">
      body {
        font: 10px sans-serif;
      }
    </style>
  </head>
  <body>

  <h2>Random</h4>
  <div id="stacked-rep"></div>

  <script>

  var repColors = ['#403153','#9e7742','#0084ab','#e30513'];
  var repColorsLight = ['#e5dae7','#deba96','#c5d7e9','#f6b89f'];
  var repCandidates = ["Trump", "Cruz", "Rubio", "Kasich"];
  var carnival_colors = ["blue", "lightblue"];
    //Width and height
  var m = {top: 10, right: 10, bottom: 10, left: 10}, // margins
      h = 150 - m.left - m.right, // height
      w = 960 - m.top - m.bottom; // width
  //Create SVG element
  var svg = d3.select("#stacked-rep")
      .append("svg")
      .attr("width", w)
      .attr("height", h);
      // Add a group for each row of data

  var data = [
            [{
              "state": 19,
              "x": "Trump1",
              "y": 2000
            }],
            [{
              "state": 33,
              "x": "Trump2",
              "y": 3000
            }]
        ];

var groups = svg.selectAll("g")
  .data(data)
  .enter()
  .append("g")
  .classed("g_stacked_elements", true)
  // .attr("class", "g_stacked elements")
  .attr("transform", "translate(" + m.left + ",0)");


  function cumulChart(id, dataset) {


      // Set up stack method
      var stack = d3.layout.stack();
      //Data, stacked
      stack(dataset);
      // console.log("the data sum is:", d3.sum(dataset, function(d) {return d[0].y;}));
      // Set up scales
      var xScale = d3.scale.ordinal()
        .domain(d3.range(dataset[0].length))
        .rangeRoundBands([0, h], 0.2); // This is actually the Y scale (candidates)
      var yScale = d3.scale.linear()
        .domain([0, 
          d3.sum(dataset, function(d) {return d[0].y;})*1.2])
        .range([0, w]); // This is actually the X Scale (States)
      // console.log(xScale);
      // Add a rect for each data value

      groups_w_data = svg.selectAll("g")
                .data(data);


      var rects = groups_w_data
        .selectAll("rect")
        .data(function(d) { return d; });

      rects.enter()
        .append("rect")
        .attr("class", "stacked")
        .attr("stacked_state", function(d) { return "st"+ d.state; })
        .attr("x", function(d) {
          return yScale(d.y0);
        })
        .attr("y", function(d, i) {
          return xScale(i);
        })
        .attr("width", function(d) {
          return yScale(d.y);
        })
        .attr("height", xScale.rangeBand())
        .style("fill", function(d, i) {
          if (d.state == 19){
            return carnival_colors[1];
          }
          else {
            return carnival_colors[0];
          }
        })
        .style("stroke", function(d, i) {
          if (d.state == 19){
            return d3.rgb(carnival_colors[1]).darker() ;
          }
          else {
            return d3.rgb(carnival_colors[0]).darker() ;
          }
        })
        /*.on("mouseover", function(d) {
          console.log(d.state);
        })*/;

        // transition
        rects.transition() // this is to create animations
          .duration(500) // 500 millisecond
          .ease("bounce")
          .delay(500)
          // .attr("class", "stacked")
          // .attr("stacked_state", function(d) { return "st"+ d.state; })
          .attr("x", function(d) {
            console.log("This is the X value: ", yScale(d.y0));
            return yScale(d.y0);
          })
          .attr("width", function(d) {
            console.log("This is the width value: ", yScale(d.y));
            return yScale(d.y);
          })

  };


  cumulChart("#stacked-rep", data);

  // create a function to randomize things
  function rand_it(x){
   return Math.floor((Math.random() * x) + 1);
  };

  setInterval(function(){
    var object = [
            [{
              "state": 19,
              "x": "Trump1",
              "y": rand_it(20)
            }],
            [{
              "state": 33,
              "x": "Trump2",
              "y": rand_it(20)
            }]
        ];
    data = object;

    cumulChart("#stacked-rep", data);
    console.log(object[0][0].y,"---",object[1][0].y);
  }, 3000);

</script>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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