javascript - 更新 : D3 won't draw chart data on load

标签 javascript jquery html css d3.js

我有一个 html 表单和 d3 图表。这个想法是表单中的每个复选框代表图表上的一个条。每个栏的可见性都设置为隐藏,直到有人从表单中选择选项并且图表功能显示每个选中的复选框代表的栏。

但是,我还希望根据表单的预选复选框(在加载时标记为已选中)预加载一些栏。

问题是图表仅在更改复选框后显示条形图。

它不会在加载时显示预先选择的数据。尽管已预先选中复选框并运行与复选框在更改时调用的功能完全相同的功能(它在用户进行更改但未加载时有效)

为什么显示条形图的函数在加载时不起作用?为什么只有在加载后更改复选框时它才有效?

FIDDLE

HTML

  <form class="form" action="">
      <div class="buildOptions">
        <div class="instructions">Select ingredients:</div>
          <div class="selection">
            <input class="ingredientBox" type="checkbox" name="ingredient" value="bars1" onclick="showBars()" checked="checked"> <span class="ingredientBoxText"style="border-color:#bf812d;">bar 1</span>
          </div>

         </div>
         </form>

JS

var activeData =[];
 function showBars(){
      // variables //


      //Get all lines from chart and place in an array
      var bars = []
      //Grab all checkbox selections
      var selected = document.getElementsByName("ingredient");

      //// Reset chart if needed ////

      //Empty the activeData variable
      activeData=[];

        //loop through all hte lines and make them hidden
      for (var i=0; i<lines.length; i++){
        bars[i].style.visibility="hidden";
      }

      /// Use input to draw chart ///

      //loop through check box values
      for (var i=0; i<selected.length; i++) {
        //If a checkbox is checked add the value to the activeData array
        if (selected[i].checked){
          activeData.push(selected[i].value)
          //take the name of the active checkbox and edit it to coincide with id of lines
          var newId = selected[i].value.replace('1','');
          //Use line id to to make appropriate line visible
          var activeBar =document.getElementById(newId)
          activeBar.style.visibility="visible"
        }
      }
    }

function drawChart(){
    var margin = {top: 20, right: 160, bottom: 35, left: 30};
var width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
var svg = d3.select("body")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
/* Data in strings like it would be if imported from a csv */
var data = [
  { year: "2006", redDelicious: "10", mcintosh: "15", oranges: "9", pears: "6" },
  { year: "2007", redDelicious: "12", mcintosh: "18", oranges: "9", pears: "4" },
  { year: "2008", redDelicious: "05", mcintosh: "20", oranges: "8", pears: "2" },
  { year: "2009", redDelicious: "01", mcintosh: "15", oranges: "5", pears: "4" },
  { year: "2010", redDelicious: "02", mcintosh: "10", oranges: "4", pears: "2" },
  { year: "2011", redDelicious: "03", mcintosh: "12", oranges: "6", pears: "3" },
  { year: "2012", redDelicious: "04", mcintosh: "15", oranges: "8", pears: "1" },
  { year: "2013", redDelicious: "06", mcintosh: "11", oranges: "9", pears: "4" },
  { year: "2014", redDelicious: "10", mcintosh: "13", oranges: "9", pears: "5" },
  { year: "2015", redDelicious: "16", mcintosh: "19", oranges: "6", pears: "9" },
  { year: "2016", redDelicious: "19", mcintosh: "17", oranges: "5", pears: "7" },
];
var parse = d3.time.format("%Y").parse;
// Transpose the data into layers
var dataset = d3.layout.stack()(["redDelicious", "mcintosh", "oranges", "pears"].map(function(fruit) {
  return data.map(function(d) {
    return {x: parse(d.year), y: +d[fruit]};
  });
}));
// Set x, y and colors
var x = d3.scale.ordinal()
  .domain(dataset[0].map(function(d) { return d.x; }))
  .rangeRoundBands([10, width-10], 0.02);
var y = d3.scale.linear()
  .domain([0, d3.max(dataset, function(d) {  return d3.max(d, function(d) { return d.y0 + d.y; });  })])
  .range([height, 0]);
var colors = ["b33040", "#d25c4d", "#f2b447", "#d9d574"];
// Define and draw axes
var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left")
  .ticks(5)
  .tickSize(-width, 0, 0)
  .tickFormat( function(d) { return d } );
var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .tickFormat(d3.time.format("%Y"));
svg.append("g")
  .attr("class", "y axis")
  .call(yAxis);
svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);
// Create groups for each series, rects for each segment 
var groups = svg.selectAll("g.cost")
  .data(dataset)
  .enter().append("g")
  .attr("class", "cost")
  .style("fill", function(d, i) { return colors[i]; });
var rect = groups.selectAll("rect")
  .data(function(d) { return d; })
  .enter()
  .append("rect")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) { return y(d.y0 + d.y); })
  .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
  .attr("class", "bars")
//.attr("id", dataset[0][0])
  .attr("width", x.rangeBand())
  .on("mouseover", function() { tooltip.style("display", null); })
  .on("mouseout", function() { tooltip.style("display", "none"); })
  .on("mousemove", function(d) {
    var xPosition = d3.mouse(this)[0] - 15;
    var yPosition = d3.mouse(this)[1] - 25;
    tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
    tooltip.select("text").text(d.y);
  });
// Draw legend
var legend = svg.selectAll(".legend")
  .data(colors)
  .enter().append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) { return "translate(30," + i * 19 + ")"; });

legend.append("rect")
  .attr("x", width - 18)
  .attr("width", 18)
  .attr("height", 18)
  .style("fill", function(d, i) {return colors.slice().reverse()[i];});

legend.append("text")
  .attr("x", width + 5)
  .attr("y", 9)
  .attr("dy", ".35em")
  .style("text-anchor", "start")
  .text(function(d, i) { 
    switch (i) {
      case 0: return "Anjou pears";
      case 1: return "Naval oranges";
      case 2: return "McIntosh apples";
      case 3: return "Red Delicious apples";
    }
  });
// Prep the tooltip bits, initial display is hidden
var tooltip = svg.append("g")
  .attr("class", "tooltip")
  .style("display", "none");

tooltip.append("rect")
  .attr("width", 30)
  .attr("height", 20)
  .attr("fill", "white")
  .style("opacity", 0.5);
tooltip.append("text")
  .attr("x", 15)
  .attr("dy", "1.2em")
  .style("text-anchor", "middle")
  .attr("font-size", "12px")
  .attr("font-weight", "bold");
}
drawChart();
showBars();

CSS

svg {
    font: 10px sans-serif;
    shape-rendering: crispEdges;
  }
  .axis path,
  .axis line {
    fill: none;
    stroke: #000;
  }

  path.domain {
    stroke: none;
  }

  .y .tick line {
    stroke: #ddd;
  }
.bars{
    visibility:hidden;
}

最佳答案

请看this link显示负载数据。我认为 css 属性 .bars - 覆盖了绘制的条。因此删除该属性。

.bars{
            visibility:hidden;
        }

我重写了 showBars 函数以显示条形和隐藏条形。此外,当您查看 fiddle 链接时,它会显示未定义错误行。所以你可能想要添加行数据。

    function showBars() {
         // variables //
        var selected = document.getElementsByName("ingredient");
      for (var i=0; i<selected.length; i++) {
      //If a checkbox is checked add the value to the activeData array
      if (selected[i].checked === false){
         d3.selectAll(".cost").style("visibility","hidden");
      }

      if(selected[i].checked === true) {
          d3.selectAll(".cost").style("visibility","visible");

      }
}

关于javascript - 更新 : D3 won't draw chart data on load,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32344619/

相关文章:

javascript - Phonegap 本地通知不执行任何操作

javascript - D3 JS Sankey图中的圆环图

javascript - jQuery - 提交表单联系人后的占位符值

javascript - 我想在 jquery 中加载页面时隐藏所有字段

html - 音频不在 html 中播放

javascript - javascript中的对象数组

javascript - 如何从 jQuery UI slider 获取值?

jquery - 跨域 jsonp 的基本操作方法

html - 仅使用 CSS float 我的 div

javascript - 如何在 Bootstrap 上创建多选下拉列表?