2013-09-26 5 views
1

Я в настоящее время работает над расширением Д3, например рэп, представленную здесь:D3.js TreeMap Layout

https://github.com/ralfstx/rap-d3charts

на TreeMap графике. Я не хочу вдаваться в детали, если не нескреб. Конкретная проблема возникает, когда я пытаюсь запустить шаблон treemap в моей структуре. Эта структура состоит из «Treemap» в качестве корня с массивом «children», содержащим все прямые дочерние элементы root с типом «ChartItem». В них также есть дети. Каждый элемент диаграммы содержит числовое значение «значение».

Я надеюсь, что это не должно смущать. Дело в том, что я понятия не имею, для чего предназначены разные атрибуты treemap. Конфигурация ниже только один, который «работает», показывая мне только дети, прикрепленные к корню (TreeMap -> это)

  • Я хотел бы предположить, что я не нужен .value атрибут поскольку мои узлы уже содержат «значение». Это неправильно?

  • То же самое с «детьми» и атрибутом «узлы»

  • Я понятия не имею, как установить эти атрибуты. Я знаю примеры d3 TreeMap и ссылки API, но они ничем не помогают мне ..

    var treemap = d3.layout.treemap() 
    .size([500,300]) 
    .padding(4) 
    .children(function(d) { return d }) 
    .value(function(d){return d.value}) 
    .nodes(this.children); 
    
    
    
        var selection = this._layer.selectAll("g.item") 
    
        var color = d3.scale.category20c(); 
        console.log(this); 
        console.log(treemap); 
    
        var cells = selection 
        .data(treemap) 
        .enter() 
        .append("svg:g") 
        .attr("class", "item") 
        .append("rect") 
        .attr("x", function(d){return d.x;}) 
        .attr("y", function(d){return d.y;}) 
        .attr("width", function(d){return d.dx;}) 
        .attr("height", function(d){return d.dy;}) 
        .attr("fill", function(d){return color(d.parent) }) 
        .attr("stroke", "black") 
        .attr("stroke-width",1); 
    
        var textfields = selection 
        .append("svg:text") 
        .attr("opacity", 1.0) 
        .attr("x", function(d){return d.x;}) 
        .attr("y", function(d){return d.y+20;}) 
        //.text(function(d){return d.children ? null : d._text;}); 
        .text(function(d){return d._text;}); 
    

Я был бы признателен за любую помощь, особенно какое-то объяснение, как макет TreeMap будет использоваться

Заранее спасибо.

+0

У вас есть объект Treemap, который вы можете поделиться с нами? Структура. – cbayram

ответ

3

.nodes(root) и .links(nodes) используются для получения массива/списка узлов и ссылок.

Обычно вы указываете свой основной/корневой объект данных или подэлемент вашего дерева функции узлов и используете извлеченные из него узлы, чтобы перейти к функции ссылок, чтобы определить узлы и ссылки, представляющие интерес.

Последние упомянутые функции .children(childrenAccessorFunction) и .value(valueAccessorFunction) рассказывают, как получить доступ к дочерним элементам узла в структуре данных и как получить доступ к значению вашего узла в вашей структуре данных соответственно. Если не указано, d3 будет использовать node.children, чтобы получить дочерний массив узла и node.value, чтобы получить значение вашего узла. Рассмотрим приведенный ниже пример того, что я только что сказал:

var family= { 
    "name": "Fred", 
    "age": 81, 
    "kids": [ 
    { 
     "name": "Becky", 
     "age": 51, 
     "kids": [ 
     {"name": "John", "age": 15}, 
     {"name": "Jill", "age": 11} 
     ] 
    } 
    ] 
} 

var treemap = d3.layout.treemap() 
    .children(function(d) { return d.kids}) // instructs the algorithm to find children by looking for node.kids instead of the default node.children 
    .value(function(d) { return d.age; }) // similarly, value of the nodes is the age attribute of the node 

// now whenever treemap has gone through and set up your structure, you can call 
var persons = treemap.node(family) // to get all the people in the family (flat structure) 
// each person object will have (after d3 enriches it) 
// * parent - the parent node, or null for the root. 
// * children - the array of child nodes, or null for leaf nodes. 
// * value - the node value, as returned by the value accessor. 
// * depth - the depth of the node, starting at 0 for the root. 
// * x - the minimum x-coordinate of the node position. 
// * y - the minimum y-coordinate of the node position. 
// * dx - the x-extent of the node position. 
// * dy - the y-extent of the node position. 

var relationship = treemap.links(persons) // this will give you the link nodes which will be objects with the following attributes 
// * source - the parent node (as described above). 
// * target - the child node. 

Надеюсь, что это имеет смысл.

Смежные вопросы