使用D3从数组创建路径

时间:2015-08-11 14:19:15

标签: javascript arrays json d3.js svg

在D3中,我需要从JSON对象数组生成路径。但是,我一直在线路功能上遇到错误,我之前已经多次见过成功。数组结构如下:

_arrays: [{key: "data name", values: [0, 1, 5, 4...]}...]
coords:  [{x: 37, y: 58}...]

_xOffset确定图表开始时特定数据集值的返回距离。

    /* Draws each of the paths. The outer loop accounts for each individual
     * data set (e.g. "orange"), while the inner loop inputs the current data
     * set's values as y-coordinates, and their indices as x-coordinates.
     * Takes the current scale of the graph into account when drawing.
     */
    _arrays.forEach(function(d, i) {
        // e.g. [20, 13, 34] becomes (0, 20), (1, 13), and (2, 34).
        if (Array.isArray(d.values)) {
            var length = d.values.length;
            var coords = [];

            // The user can't pan outside of graph bounds!
            _xOffset = (_xOffset > length - _width) ? length - _width : _xOffset;
            _xOffset = (_xOffset < 0) ? 0 : _xOffset;

            for(var j = length - _xOffset; j > length - _width && j > 0; j--) {
                coords.push({x: j - (length - (_xOffset + _width)),
                             y: d.values[j]});
            };

            // Reads and scales current section of graph.
            var lineFunction = d3.svg.line()
                .x(function(d) {
                    return x(d.x + _margins.left + 1);
                })
                .y(function(d) {
                    return y(_height + _margins.top - (d.y/* * _yScale*/));
                })
                .interpolate("linear");

            _svg.append("path")
                     .attr("d", lineFunction(coords))
                     .attr("stroke-width", 1         )
                     .attr("stroke",       _colors[i])
                     .attr("fill",         "none"    );
        }
    });

我的逻辑是我首先从当前数据集的values数组生成一个JSON坐标数组,索引为x坐标,值为y坐标。最后,d3.svg.line()函数读取坐标并获取X和Y值 - 但事实并非如此。

0 个答案:

没有答案