Adding a chart legend in D3

后端 未结 2 1649
温柔的废话
温柔的废话 2020-12-29 18:29

I am having trouble adding a chart legend to my d3js chart. Here is my current approach:

var legend = svg.append(\"g\")
  .attr(\"class\", \"legend\")
  .att         


        
2条回答
  •  被撕碎了的回忆
    2020-12-29 19:14

    You need to bind data to the nodes (rectangles and text elements) that make up the legend.

    Currently you get an error when trying to style rectangles:

    Uncaught TypeError: Cannot read property '1' of undefined 
    

    The reason: there's no bound data

    legend.append("rect")
          /*...*/
          .style("fill", function(d) { 
             // d <---- is undefined
             return color_hash[dataset.indexOf(d)][1] 
          });
    

    Notice that D3 focuses on data transformation and operates on selections. So, first select a set of nodes and then bind data

    legend.selectAll('rect')
          .data(dataset)
          .enter()
    

    Once you enter the selection with enter, you can add nodes and apply properties dynamically. Notice that to avoid creating rectangles on top of others, when setting the y property pass the i counter and multiply it by an integer.

      /*.....*/
          .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 = color_hash[dataset.indexOf(d)][1];
             return color;
          });
    

    Here's the fixed example: http://jsbin.com/ubafur/3

提交回复
热议问题