使用D3的路径生成器。如何为他们分配数据?

时间:2016-01-25 09:08:12

标签: javascript d3.js svg

我目前正在尝试使用D3.js

实现折线图

D3文档包含以下示例:

var line = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("basis");

g.append("path")
    .attr("d", line);

...并说"无论绑定到哪个数据g(在本例中)都将被传递给行实例。"

"边界数据"是什么意思?

我已经获得了以下代码:

var lineGen = d3.svg.line()
                 .x(function(d, i) {
                    return xScale(i);
                 })
                 .y(function(d) {
                    return HEIGHT - yScale(d);
                 })
                 .interpolate('basis');
    var lineVal = lineGen(data);

    svg.append('path').attr('d', lineVal)
                      .attr({
                        'fill': 'none',
                        'stroke': 'black',
                        'stroke-width': '3'
                      });

使用lineGen(数据)我生成一个字符串。然后我将此字符串分配给attr-setter。

但官方文件中解释的方式并不奏效。

我需要做什么才能直接将数据绑定到SVG元素?

svg.data(数据)不起作用。我已经尝试过了。

更新

我在教程中找到了解决方案。

// Data-structure. In this case an 
//   one-dimensional array.
var data = [ 22, 31, 29, 32, 21, 38, 30 ];

svg.append('path')
    // Assign the data-structure as ONE
    //   element an array-literal.
    .data([data])
    .attr('d', lineGen)
    .attr({
      'fill': 'none',
      'stroke': 'black',
      'stroke-width': '3'
    });

通过将数据结构指定为array-literal的元素 整个数据绑定到一个元素。

此技术的替代方法是使用selection.datum()。 https://github.com/mbostock/d3/wiki/Selections#datum

1 个答案:

答案 0 :(得分:0)

在d3中,数据与选择结合。您可以使用进入和退出选择来为传入数据创建新节点,并删除不再需要的传出节点。

在您的示例中,您应该尝试如下所示。

var line = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("basis");

g.selectAll("path") //Selects all the elements that match the specific selector, here elements having path tag
    .data(data)  //The data operator joins the specified array of data with the current selection.
    .enter() //The enter selection contains placeholders for any missing elements. Here it has placeholders for n path elements where n is the length of data array.
    .append("path") //For each placeholder element created in the previous step, a path element is inserted.
    .attr("d", line); //The first param of line function would be the data (corresponding array element) bond to the current path element. And the second param is the data index.

要了解有关d3中数据绑定的更多信息,请参阅:Binding-data-to-dom-elements

修改: 要创建绑定了数据的单个路径元素,请尝试如下所示。

g.append("path")
 .datum(dataObj) //Where dataObj is data[i]
 .attr("d", line);