将d3序列sunburst示例应用于新数据得到js错误

adapting d3 sequences sunburst example to new data & getting js error

本文关键字:数据 错误 js 新数据 序列 d3 sunburst 应用于      更新时间:2023-09-26

我试图从d3画廊重新利用序列sunburst示例,并且没有viz + js错误,我不知道如何修复。

"我的"代码可以在这里找到。与原版相比,我唯一的改变(基本上)是使用我自己的(现在是假的)数据来描述吸烟者的情况。请进来看医生。他们可以讨论戒烟和肺癌筛查,每一个都有自己独特的管道。

该错误来自sequences.js中的buildHierarchy()函数。这个家伙使用了原始样本数据(在该repo中提供为'sample-data.csv'——更改sequences.js的第46行以切换到该数据)。但当我把它指向我的小假数据集时,它会显示:

Uncaught TypeError: Cannot read property 'push' of undefined sequences.js:303

我已经遍历了那个函数&可以看到,它发生在该函数为csv中第一行的最后一个组件添加叶节点之后。在执行过程中,children没有设置,因此对push()的调用失败。

我不明白为什么原始数据也不会导致这个问题,或者如何修复buildHierarchy(),使其工作。

感谢您的帮助。

这应该修复它,在一些数据集上遇到了类似的问题。在创建新的子节点时,刚刚添加了children:[]。此外,它看起来会有点错误,除非你添加一个"-End"到一个元素数据位(DiscussScreening和DiscussedCessation),就像例子中Product>End

一样
function buildHierarchy(csv) {
    var root = {
        "name": "root",
        "children": []
    };
    for (var i = 0; i < csv.length; i++) {
        var sequence = csv[i][0];
        var size = +csv[i][1];
        if (isNaN(size)) { // e.g. if this is a header row
            continue;
        }
        var parts = sequence.split("-");
        var currentNode = root;
        for (var j = 0; j < parts.length; j++) {
            var children = currentNode["children"];
            var nodeName = parts[j];
            var childNode;
            if (j + 1 < parts.length) {
                // Not yet at the end of the sequence; move down the tree.
                var foundChild = false;
                for (var k = 0; k < children.length; k++) {
                    if (children[k]["name"] == nodeName) {
                        childNode = children[k];
                        foundChild = true;
                        break;
                    }
                }
                // If we don't already have a child node for this branch, create it.
                if (!foundChild) {
                    childNode = {
                        "name": nodeName,
                        "children": []
                    };
                    children.push(childNode);
                }
                currentNode = childNode;
            } else {
                // Reached the end of the sequence; create a leaf node.
                childNode = {
                    "name": nodeName,
                    "size": size,
                    "children" : []
                };
                children.push(childNode);
            }
        }
    }
    return root;
};