2012-04-21 41 views
1

我試圖渲染d3.js樹形圖樹形圖,並使用示例代碼 - http://mbostock.github.com/d3/ex/treemap.htmlD3.js - 從平面JSON層次

enter image description here

我遇到一個問題,我的源JSON是一個平坦的heirachy,因此調用treemap.nodes是錯誤的。

任何人都可以建議如何返回一個扁平的層次?

我的樣品JSON:

[ 
    {"ticker":"$GOOG","count":"82","sentiment":"9"}, 
    {"ticker":"$AAPL","count":"408","sentiment":"8"}, ... 

而且我完整的代碼至今:

d3.json("/finance/data", function(json) { 

    var w = 960, 
     h = 500, 
     color = d3.interpolateRgb("rgb(0,255,0)", "rgb(255,0,0)"); 
     //xcolor = d3.scale.linear().domain([-26,13]).range("rgb(0,255,0)", "rgb(255,0,0)"), 
     x = d3.scale.linear().domain([-26,13]).range([0, 1]), 
     stepsize = [2.46, 1.66], 
     minval = [-16.28, -16.67]; 


    var treemap = d3.layout.treemap() 
     .size([w, h]) 
     .sticky(true) 
     .value(function(d) { return d.count; }); 

    var div = d3.select("#treemap-transition").append("div") 
     .style("position", "relative") 
     .style("width", w + "px") 
     .style("height", h + "px"); 


    div.data([json]).selectAll("div") 
    .data(treemap.nodes) 
    .enter().append("div") 
     .attr("class", "cell") 
     .style("background", function(d) { return treemap_color(d.sentiment, 2.5, 10); }) 
     .call(cell) 
     .attr("text-anchor", "middle") 
     .text(function(d) { return d.children ? null : d.ticker; }); 


    function cell() { 
    this 
     .style("left", function(d) { return d.x + "px"; }) 
     .style("top", function(d) { return d.y + "px"; }) 
     .style("width", function(d) { return d.dx - 1 + "px"; }) 
     .style("height", function(d) { return d.dy - 1 + "px"; }) 
     .style("text-anchor", "middle"); 
    } 


    function treemap_color(value, stepsize, steps) { 
    if (value == 0) { 

     return "rgb(0,0,0)"; 

    } else if (value < 0) { 

     var x = Math.round((255/steps) * Math.abs(value/stepsize)); 
     return 'rgb(0,' + x + ',0)'; //DECREASE in unemployment => green 

    } else { 

     var y = Math.round( (255/steps) * value/stepsize); 
     return 'rgb(' + y + ',0,0)'; //INCREASE in unemployment => red 
    } 
    } 

}); 

欣賞任何評論。

回答

2

不確定你的意思是否持平。如果你的意思是你沒有一個「節點」 supercategory在D3,那麼你可以使用:的

.data(treemap) 

代替:

.data(treemap.nodes) 

,但沒有在你的JSON的「孩子」的屬性,你不會得到任何分層包裝。

+0

謝謝,.data(treemap)我需要什麼! – Ben 2012-04-23 12:46:14