2013-04-23 80 views
4

我遇到了幾個與我的條形圖有關的問題。目前的問題是試圖創造一個傳奇。圖例應爲全球本地(藍色&綠色)。 目前該圖例生成5個盒子 - 其中2個是彩色的。我假設它正在通過我的數據集併爲每組列生成框。我不想要這個。d3js爲條形圖創建圖例

當我得到格式化的圖例後,我希望能夠讓它交互。因此,如果他們只想看到全球,那麼他們取消選擇本地,並且圖表動態更新。我知道我需要調整它,並創建一個功能來更新數據,域等。

但是在開始這條道路之前,我想要正確地填充圖例。但是,如果傳奇解決方案能夠走上這條道路,我將不勝感激。

I have a working Fiddle you can play around with

數據源

var colors = {0: ["Local", "#377EB8"], 
      1: ["Global", "#4DAF4A"]}; 

var dataset = [ 
      {"keyword": "payday loans", "global": 1400000, "local": 673000, "cpc": "14.11"}, 
      {"keyword": "title loans", "global": 165000, "local": 160000, "cpc": "12.53" }, 
      {"keyword": "personal loans", "global": 550000, "local": 301000, "cpc": "6.14"}, 
      {"keyword": "online personal loans", "global": 15400, "local": 12900, "cpc": "5.84"}, 
      {"keyword": "online title loans", "global": 111600, "local": 11500, "cpc": "11.74"} 
     ]; 

標號碼

var legend = svg.append("g") 
    .attr("class", "legend") 
    //.attr("x", w - 65) 
    //.attr("y", 50) 
    .attr("height", 100) 
    .attr("width", 100) 
    .attr('transform', 'translate(-20,50)'); 


legend.selectAll('rect') 
    .data(dataset) 
    .enter() 
    .append("rect") 
    .attr("x", w - 65) 
    .attr("y", function(d, i) { 
     return i * 20; 
    }) 
    .attr("width", 10) 
    .attr("height", 10) 
    .style("fill", function(d) { 
     var color = colors[dataset.indexOf(d)][1]; 
     return color; 
    }); 

legend.selectAll('text') 
    .data(dataset) 
    .enter() 
    .append("text") 
    .attr("x", w - 52) 
    .attr("y", function(d, i) { 
     return i * 20 + 9; 
    }) 
    .text(function(d) { 
     var text = colors[dataset.indexOf(d)][0]; 
     return text; 
    }); 

我知道我顏色陣列/對象可能不是最有效的方式。所以我願意調整,如果它有助於解決方案。 此外,我寧願它是一個水平列表,而不是垂直。

回答

3

您需要使用colors而不是dataset作爲圖例的.data()的參數。 爲了該工作,colors必須是一個陣列,而不是一個對象:

var colors = [ ["Local", "#377EB8"], 
       ["Global", "#4DAF4A"] ]; 

用於創建圖例的代碼變爲:

var legendRect = legend.selectAll('rect').data(colors); 

legendRect.enter() 
    .append("rect") 
    .attr("x", w - 65) 
    .attr("width", 10) 
    .attr("height", 10); 

legendRect 
    .attr("y", function(d, i) { 
     return i * 20; 
    }) 
    .style("fill", function(d) { 
     return d[1]; 
    }); 

var legendText = legend.selectAll('text').data(colors); 

legendText.enter() 
    .append("text") 
    .attr("x", w - 52); 

legendText 
    .attr("y", function(d, i) { 
     return i * 20 + 9; 
    }) 
    .text(function(d) { 
     return d[0]; 
    }); 

比照the updated fiddle

+0

不錯。 而我將如何使其水平? – EnigmaRM 2013-04-23 21:31:03

+0

[像這樣?](http://jsfiddle.net/juY5E/9/)我認爲旋轉文本雖然有點尷尬,但閱讀... – ValarDohaeris 2013-04-23 22:02:59

+0

此外,如果你想做動態更新,你應該瞭解[常規更新模式](http://bl.ocks.org/mbostock/3808218)! – ValarDohaeris 2013-04-23 22:07:18