Unable to display legend for a quantile scale in D3

余生颓废 提交于 2020-01-06 17:36:45

问题


I am trying to display a legend for a heat map I have created, but am unable to do that. Here is my HTML

<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>

Here is the code for the legend I am trying to create

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];
        });

When I use Chrome Developer Tools to inspect the element, I see that the required g elements have been created but they all have dimensions of 0x0.

I read somewhere that rect elements can only be appended to an svg element, which is why I changed my HTML code to include an svg element with a class of legend, however I am still not getting any result.

Here is a link to the codepen for this program

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


回答1:


I have modified your pen like 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);

Hope this helps, good luck!



来源:https://stackoverflow.com/questions/41439050/unable-to-display-legend-for-a-quantile-scale-in-d3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!