d3.js:如何根据子项和父项值

时间:2015-09-18 10:19:15

标签: javascript d3.js charts partition

我正在尝试在D3中构建一个基本的冰柱分区树,我似乎无法获得值函数来做我想要的。基本上,我希望每个节点根据它的值和它的子节点的大小来调整大小。如上所述: d3.js: size of parents = sum of size of children,默认行为根据子节点的总和来调整节点大小。但是,我发现它只查看叶节点,然后根据这些节点调整所有节点的大小。

我已经对我希望我的节点调整为JSON值(totalMass)的值进行了硬编码,该值已经计算了当前节点及其子节点的值。结果如下:

抱歉,我无法发布图片,但我可以对其进行描述:

What I would like:

Root (12 = 5 + Children (3+4))
    Child1 (3 = 1 + Children (2))
        Leaf (2)
    Child2 (4 = 2 + Children (2))
        Leaf (2)
        
What I get:

Root (4)
    Child1 (2)
        Leaf (2)
    Child2 (2)
        Leaf (2)

感谢您的帮助。 所以,我希望一切都与根节点的实际值成比例,因此会有一些空的空格(因为每个节点的值将高于它的子节点的总和)。这也是我的实际数据的简化示例,并非所有叶节点都不在同一级别上。

有没有让值函数像这样工作,还是我必须手动调整图表节点的大小?

到目前为止,这是我的代码(在Typescript中):

this.svg = d3.select(this.container).append("svg")
            .attr("width", this.width + this.margin.right + this.margin.left)
            .attr("height", this.height + this.margin.top + this.margin.bottom)
            .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");          

        this.rectPartition = this.svg.append("g")
            .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")")
            .classed("rect_partition", true);

        // TODO: filter children such that accounts for leaf children of same category
        this.partition = d3.layout.partition()
            .children((d: ChartNode) => {
                var filteredChildren = [];
                if (d.children) {
                    d.children.forEach(child => {
                        if (this.nodeContainsCategory(child, ProductsCategory)) filteredChildren.push(child);
                    });
                    return filteredChildren;
                }
                else return null;
            })
            .value((d: ChartNode) => d.totalMass)
            .sort((a: ChartNode, b: ChartNode) => {
                //first sort by owner, then sort by short name
                if (a.owner === b.owner) return (a.shortName > b.shortName) ? 1 : -1;
                else return (a.owner > b.owner) ? 1 : -1;
            });

2 个答案:

答案 0 :(得分:0)

嗯,说实话我和你有同样的问题。显然有一个关于这个问题的拉取请求:https://github.com/mbostock/d3/pull/574。还有另一个解决方案是迈克博斯托克自己在使用虚拟节点的线程评论。我还在努力解决这个问题,但是如果你看一下可能会帮助你(如果你还有这个问题)。

答案 1 :(得分:-1)

我认为Zoomable气泡图最符合您的要求。你可以使用d3 pack布局。

这是此构造的官方D3链接.. Click here

我希望我的建议可以帮到你..