2017-01-02 151 views
1

如何將圖例添加到圖表(see fiddle)?我嘗試按如下方式定義圖例,但圖表消失(請參閱this fiddle)。如何將圖例添加到圖表?

var height = 900, width = 900; 
var gridSize = Math.floor(width/42); 
var legendElementWidth = gridSize*2; 

var legend = svg.selectAll(".legend") 
       .data([0].concat(colorScaleDomain.quantiles()), function(d) { return d; }); 

legend.enter().append("g") 
    .attr("class", "legend"); 

legend.append("rect") 
.attr("x", height) 
.attr("y", function(d, i) { return legendElementWidth * (i-0.5); }) 
.attr("width", gridSize/2) 
.attr("height", legendElementWidth) 
.style("fill", function(d, i) { return colors[i]; }); 

legend.append("text") 
.attr("class", "mono") 
.text(function(d) { return "≥ " + Math.round(d) + "%"; }) 
.attr("x", (height) + gridSize) 
.attr("y", function(d, i) { return legendElementWidth*i; }); 

legend.exit().remove(); 

回答

2

這是問題的列表:

  1. 沒有colorScaleDomain.quantiles()。應改爲colorScale.quantiles()

  2. 在沒有z索引的SVG中,元素的順序非常重要。所以,你的傳說......

    legend.enter().append("g") 
        .attr("class", "legend"); 
    

...應該來圖表的繪製代碼之後。但是,步驟,甚至可以忽略不計,這是因爲第三個問題的:

  • 你的圖例是的SVG。我糾正與:

    var svg = d3.select("body").append("svg") 
        .attr("width", diameter + 200)//adding some space in the SVG 
    
  • 而且一些幻數的傳說代碼。相應地改變它們(在大多數情況下,幻數不是一個好習慣)。

    這裏是您更新的小提琴:https://jsfiddle.net/hsq05oq9/

    +0

    謝謝。如果我需要在圖例中顯示絕對數字,該怎麼辦?此外,'colorScale'已被定義爲分位數:'ar colorScale = d3.scale.quantile() .domain(colorScaleDomain) .range(colors);'。我稍微誤解了爲什麼需要在'.data([0] .concat(colorScale.quantiles()),function(d){return d;});''中重新運行'colorScale.quantiles() – Dinosaurius

    +0

    '分位數()'是規模。 'quantiles()'返回分位數。他們不同。 –

    +0

    哦,我不知道這個。抱歉。無論如何,如果你能指出如何在圖例中獲得絕對數字,我非常感激。 – Dinosaurius