How to update legend data in D3.js

I am working on one project where I need to display data on a US map. Here is the link to the code.

I am getting a boolean error in the output. In the attributes dropdown menu, when you first select the attribute as DAMAGE_PROPERTY, I get the legend I want. But as soon as you select a different attribute, the previous legend is added to the new one. You can check it from the link. I used the .remove () property in the code to remove previously added elements.

Here is my legend code -

var legendRectSize = 18;
var legendSpacing = 4;

var color = d3.scale.ordinal()
    .domain(["<10", "10-20", "20-30", "30-40", "40-50", "50-60", "60-70", "70-80", ">80"])
    .range(["#1a9850", "#66bd63", "#a6d96a","#d9ef8b","#ffffbf","#fee08b","#fdae61","#f46d43","#d73027"]);

var colorforbig=d3.scale.ordinal()
    .domain(["<100","100-1000","1000-5000","5000-50000","50000-100000","100000-500000","5000000-10000000","10000000-50000000",">50000000"])
    .range(["#1a9850", "#66bd63", "#a6d96a","#d9ef8b","#ffffbf","#fee08b","#fdae61","#f46d43","#d73027"]);

initlegend();


function initlegend(){
    Legend=d3.select("svg")
        .append("g")
        .attr("id","legend");
}

function loadlegend(){
    alert("in loadlegend");
var remove=d3.select("#legend")
    .selectAll("g")
    .remove();

console.log(remove);

var legendBox=Legend.selectAll("g")
    .data(function(){
        if(attr=="DAMAGE_PROPERTY"){
            return colorforbig.domain();
        }
        else{
            return color.domain();
        }
    })
    .enter()
    .append("g")
    .attr("class", "legend")
    .attr("transform", function(d, i) {
        var height = legendRectSize;
        var horz = 20;
        var vert = i * height;
        return "translate(" + horz + "," + vert + ")";
    });

//Append a rectangle to each legend element to display the colors from the domain in the color variable
    legendBox.append("rect")
        .attr("width", legendRectSize)
        .attr("height", legendRectSize)
        .style("fill", color)
        .style("stroke", color);

//Append a text element to each legend element based on the listed domains in the color variable
    legendBox.append("text")
        .attr("x", legendRectSize + legendSpacing)
        .attr("y", legendRectSize - legendSpacing)
        .text(function(d) { return d; });
}

      

What I want is when you select the DAMAGE_PROPERTY attribute it should show a different legend. For the other four properties, it should show a different legend. So, there are two legends.

+3


source to share





All Articles