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()
    .range(["#1a9850", "#66bd63", "#a6d96a","#d9ef8b","#ffffbf","#fee08b","#fdae61","#f46d43","#d73027"]);


function initlegend(){"svg")

function loadlegend(){
    alert("in loadlegend");


var legendBox=Legend.selectAll("g")
            return colorforbig.domain();
            return color.domain();
    .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
        .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
        .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.


source to share

All Articles