在d3中绘制上传的数据

时间:2014-03-16 17:32:58

标签: javascript html csv d3.js buttonclick

我正在尝试使用d3绘制上传的csv文件数据。但是我一直收到d3未定义的错误消息。这是代码示例。 csv文件由3列和300行组成,以逗号分隔。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>A Plot</title>

<style>
</style>

<div id="plotA"></div>
<script src="http://d3js.org/d3.v3.js"></script>

<script>

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 1000 - margin.left - margin.right,
    height = 150 - margin.top - margin.bottom;

function Graph() {

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var line1 = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.ECG); });

var svg1 = d3.select("#ecgplot").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 + ")");

d3.csv("#fileinput", function(error, data) {
  data.forEach(function(d) {
    d.date = +d.tm;
    d.A = +d.A;
    d.B = +d.B;
  });

  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain(d3.extent(data, function(d) { return d.A; }));

  svg1.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("transform", "rotate(0)")
      .attr("y", 28)
      .attr("x", 450)
      .attr("dx", ".71em")
      .style("text-anchor", "end")
      .text("Time (in second)");
  svg1.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", -35)
      .attr("x", -35)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("A");

function transition1(path1) {

var totalLength1 = path1.node().getTotalLength();

  path1
      .attr("stroke-dasharray", totalLength1 + " " + totalLength1)
      .attr("stroke-dashoffset", totalLength1)
      .transition()
      .duration(25000)
      .ease("linear")
      .attr("stroke-dashoffset", 0)
      .each("end", function() { d3.select(this).call(transition1); });
}

});

}//End of Graph Function

</script>
</head>

<body>

<form>

  Select a file: <input type="file" accept=".csv" id="fileinput">
  <input type="button" id="addButton" value="Add to CSV File" onclick="Graph()" />

</form>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我想现在可以通过为所有js代码添加超时来解决这个问题,因为你的d3 lib是从cdn加载的,可能需要几秒钟。