2016-01-23 88 views
1

我需要幫助設置D3堆疊條形圖上的標籤。我不知道如何將圖例中的顏色與數據對象中name屬性的引用進行映射。D3在圖例上設置標籤

我這裏有一個的jsfiddle: http://jsfiddle.net/Lhs3e7xk/1/

特別是我需要幫助的代碼是傳說功能:

function updateLegend(dt) { 
    var legend = svg.selectAll(".legend") 
    .data(color.domain()) // I tried dt as well. 
    .enter().append("g") 
    .attr("class", "legend") 
    .attr("transform", function(d, i) { 
     return "translate(0," + i * 20 + ")"; 
    }); 

    legend.append("rect") 
     .attr("x", width - 18) 
     .attr("width", 18) 
     .attr("height", 18) 
     .style("fill", color); 

    legend.append("text") 
     .attr("x", width - 24) 
     .attr("y", 9) 
     .attr("dy", ".35em") 
     .style("text-anchor", "end") 
     .text(function(d, i) { 
     console.log(d) 
     return color(d.name) 
     }); 
} 

輸出應該在數據集的名稱屬性的值以及與該組相關的顏色。

固定MBS [Color01]
浮動MBS [Color02]
CMO [Color03]

謝謝!

回答

1

取而代之的是

.text(function(d, i) { 
    console.log(d) 
    return color(d.name) 
    }) 

做文本功能是這樣的:

.text(function(d, i) { 
    if(i==0) 
    return "Fixed MBS" 
    if(i==1) 
    return "Floating MBS" 
    if(i==2) 
    return "CMO" 

    }); 

工作實例here

編輯

對於使用數據設置的傳說//您的動態圖例數據集 var legends = [「固定MBS」,「浮動MBS」,「CMO」];

function updateLegend(dt) { 
    var legend = svg.selectAll(".legend") 
    .data(legends)//pass the lgend data 
    .enter().append("g") 
    .attr("class", "legend") 
    .attr("transform", function(d, i) { 
     return "translate(0," + i * 20 + ")"; 
    }); 

    legend.append("rect") 
     .attr("x", width - 18) 
     .attr("width", 18) 
     .attr("height", 18) 
     .style("fill", function(d, i){return color(i)});//color based on index 

    legend.append("text") 
     .attr("x", width - 24) 
     .attr("y", 9) 
     .attr("dy", ".35em") 
     .style("text-anchor", "end") 
     .text(function(d, i) { 
     return d;//return the array data 
     }); 
} 

工作代碼here

+0

感謝西里爾,這工作,但有動態設置標籤的方法嗎?實際上,我可能會有超過3個部分,我也希望將此代碼重用於其他圖表,以便標籤可能會更改。也許我可以將標籤提取到不同的數組中,但理想情況下,標籤應該來自數據集。沒有? – vdiaz1130

+0

檢查編輯部分我已經使其動態基於數組 – Cyril