2017-01-03 74 views
0

我試圖顯示我創建的熱圖的圖例,但無法做到這一點。這是我的HTML無法在D3中顯示分位數的圖例

<html> 
    <head> 
    <title>Heat Map Data Visualization</title> 
    </head> 
    <body> 
    <div class='chart-area'> 
     <svg class='chart'></svg> 
     <svg class='legend'></svg> 
    </div> 
    </body> 
</html> 

這裏是傳說我想創建

var legend = d3.select('.legend') 
       .data([0].concat(colorScale.quantiles()), function(d){ 
        return d; 
       }); 

    legend.enter() 
     .append('g') 
     .attr('class', 'legend-element'); 

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

當我使用Chrome開發者工具來檢查元素的代碼,我看所需要的摹內容已經創建,但它們都具有0x0的尺寸。

我在某處讀到rect元素只能附加到svg元素,這就是爲什麼我改變了我的HTML代碼以包含一個類圖例的svg元素,但是我仍然沒有得到任何結果。

這裏是一個鏈接到codepen對這一計劃

http://codepen.io/redixhumayun/pen/eBqamb?editors=0010

回答

2

我已經修改了你的筆就像this

// Save the legend svg in a variable 
// also changed the translate in order to keep the legend within the svg   
// and place it on the right side just for the example's sake 
    var legendSvg = svg.append('g') 
     .attr('class', 'legend') 
     .attr("transform","translate("+ (width - 40) + ",20)") 

// Define the legend as you did 
var legend = d3.legendColor() 
       .useClass(true) 
       .shape('rect') 
       .orient('vertical') 
       .title('Temperature Variance') 
       .shapeWidth(legendElementWidth) 
       .scale(colorScale); 

// And then call legend on the legendSvg not on svg itself 
legendSvg.call(legend); 

希望這會有所幫助,祝你好運!