D3:数据,输入,追加模式将数据添加到外部块

Tob*_*ael 5 javascript enter append d3.js

我正在使用D3 javascript库来呈现一些基本的Web图表.我想在块中添加三个<path>元素<svg>,但D3将元素添加到<html>块的末尾.这是完整的html源代码:

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="d3.v2.js"></script>
<script>
var chartData = [ 1, 2, 3 ];
d3.select("html").select("body").append("svg")
  .data(chartData, function(d) { console.log("data d:", d); return d; })
  .enter()
    .append("path")
      .attr("d", function(d) { return d; });
</script>
</body>
Run Code Online (Sandbox Code Playgroud)

Chrome的开发者控制台显示生成的html为:

<html><head><meta charset="utf-8">
<style type="text/css"></style></head><body>
<script src="d3.v2.js"></script>
<script>
var chartData = [ 1, 2, 3 ];
d3.select("html").select("body").append("svg")
  .data(chartData, function(d) { console.log("data d:", d); return d; })
  .enter()
    .append("path")
      .attr("d", function(d) { return d; });
</script><svg></svg>
</body><path d="1"></path><path d="2"></path><path d="3"></path></html>
Run Code Online (Sandbox Code Playgroud)

<svg>块被创建,但由于某些原因,该<path>块之外的它.如何更正此错误,并将它们放在<svg>它们所属的位置?

mcc*_*nnf 5

首先,你应该有一个只引用svg的高级变量.其次,您应该在创建SVG时指定SVG的高度和宽度.您无需指定选择html,因此:

var width = 400,
    height = 300;
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用该svg变量追加路径.建议您将路径组合在一起(因此"g"首先附加路径).您还应该selectAll为路径执行操作,因为您要将要添加的数据绑定到路径元素.所以:

svg.append("g").selectAll("path")
    .data(chartData)
  .enter().append("path")
    .attr("d", function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)

我在这里推荐D3教程:http://alignedleft.com/tutorials/d3/