简体   繁体   中英

D3 not rendering simple bar chart in jade

I'm trying to create a simple bar chart from some dynamically generated data, but I can't get D3 to render the chart. Here's my jade layout:

extends layout

block content
  h1= title
  script(src="http://d3js.org/d3.v3.min.js")
  p Coverage: #{coverage}
  .chart
  script(type='text/javascript').
    var id =!{JSON.stringify(id)};
    var file="temp/"+id+".coverageHist.txt";
    var dataset = [];
    d3.tsv(file, function(data) {
      data.forEach(function(d) {
        dataset.push(d[0]);
      })
    });
    console.log(dataset);
    d3.select(".chart").selectAll("div")
      .data(dataset)
      .enter()
      .append("div")
      .style("height", function(d) {
        var barHeight = d * 5;
        return barHeight + "px";
      });

And here's the rendered HTML:

<!DOCTYPE html><html><head><title>Results</title><link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css"><link rel="stylesheet" href="/bootstrap/css/bootstrap-theme.min.css"><link rel="stylesheet" href="/stylesheets/style.css"><link rel="stylesheet" href="/bootstrap/js/bootstrap.min.js"></head><body><h1>Results</h1><script src="http://d3js.org/d3.v3.min.js"></script><p>Coverage: 1.98612
</p><div class="chart"></div><script type="text/javascript">var id ="123c52299cd5cac9b858890be1e4271908bd93ac";
var file="temp/"+id+".coverageHist.txt";
var dataset = [];
d3.tsv(file, function(data) {
  data.forEach(function(d) {
    dataset.push(d[0]);
  })
});
console.log(dataset);
d3.select(".chart").selectAll("div")
  .data(dataset)
  .enter()
  .append("div")
  .style("height", function(d) {
    var barHeight = d * 5;
    return barHeight + "px";
  });</script></body></html>

Any ideas? I push the values to an array and then plot them using example code from the Bar Chart tutorial

I'm pretty sure that d3.tsv is asynchronous, so you probably don't have any data in dataset when the rest of your d3 code runs.

Try putting everything from console.log(dataset) onwards in the callback for d3.tsv .

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