2013-07-09 11 views
1

這是一個技術/優化問題。使用SA和bl.ocks中的許多源代碼,我可以獲得帶有旋轉文本的水平圖例,如下所示。我爲了所有權原因而修剪它。D3:改善我的形狀文本鏈接

horizontal legend

這裏是我使用的代碼:

var svg_legend = d3.select("body").append("svg") 
    .attr("width", width+margin.left) 
    .attr("height", 180) 
    .append("g") 
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

rects=svg_legend.selectAll("rect") 
.data(coldomain) 
.enter().append("rect") 
.attr("height", 15) 
.attr("x", function(d, i) { return (i+1)*((width-margin.left)/coldomain.length); }) 
.attr("width", 15) 
.style("fill", color);  

text = svg_legend.selectAll("text") 
    .data(coldomain) 
    .enter().append("text") 
    .text(function(d){return d}) 
    .style("fill", 'black') 
    .attr("y", 60) 
    .attr("x", 0) 
    .attr("text-anchor", "end") 
    .style("font-size", "12px") 
    .attr("transform", function(d, i) { return "translate(" + (i)*((width-margin.left)/coldomain.length)+",0) rotate(-65," + 0+"," + 0+") "; }) 

隨着所以這個作品,但好像我應該能夠做到的矩形和文本在一個通,讓你不必擔心讓他們排隊,B/C文本會以某種方式動態地與矩形同步。有沒有更好的方法來達到上述目的?

感謝您的任何建議。

回答

2

一種方法可能是在主組下創建組,將數據綁定到這些組,將它們進行轉換,然後將矩形和文本附加到每個組。這一戰略的要點是:

var svg = d3.select('body').append('svg'), 
    grp = svg.append('g') 
     .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); 

// Compute the actual translation and replace the zeros 
var groups = grp.selectAll('g') 
    .data(coldomain) 
    .enter() 
    .append('g') 
    .attr('transform', function(d) { return 'translate(0, 0)'; }); 

// The rectangles are now relative to the parent group 
groups.append('rect') 
    .attr('x', 0) 
    .attr('y', -10) 
    .attr('width', 10) 
    .attr('height', 10); 

// The text position is now relative to the parent group 
groups.append('text') 
    .attr('x', 0) 
    .attr('y', 10) 
    .text(function(d) { return d.name; }); 

綁定到該組的數據項被傳遞給他們的孩子的元素,在這種情況下,recttext元素。

+0

謝謝!我會試試看。 MB在相關主題上推薦了一些非常類似的東西,但我無法想象它將如何實現。讓我們假設它的作品並接受這個答案:)。 – ouonomos

+0

事實上,它確實奏效。再次感謝。 – ouonomos

+0

我正在添加文章,以便問題和答案更加完整:http://bost.ocks.org/mike/selection/ –