Ad

D3 Set Labels On Legend

- 1 answer

I need help setting the labels on a D3 stacked bar chart. I'm not sure how to map the color in the legend with a reference to the name property in the data object.

I have a JSFiddle here: http://jsfiddle.net/Lhs3e7xk/1/

The code in particular I need help with is the legend function:

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

The output should be the value for the name property in the data set and the color associated with that group.

Fixed MBS [Color01]
Floating MBS [Color02]
CMO [Color03]

Thank you!

Ad

Answer

Instead of this

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

do the text function like this:

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

  });

Working example here

EDIT

For setting legends using data //your dynamic legend data set var legends = ["Fixed MBS", "Floating 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
      });
}

Working code here

Ad
source: stackoverflow.com
Ad