如何更新D3.js

时间:2017-03-26 08:15:16

标签: javascript d3.js legend

我正在开展一个项目,我需要在美国地图上绘制数据。 以下是代码的link

我在输出中遇到逻辑错误。在属性的下拉菜单中,当您首次选择属性为DAMAGE_PROPERTY时,我会得到我想要的图例。但是一旦选择了不同的属性,先前的图例就会附加到新的图例中。您可以在链接上测试它。我在代码中使用了.remove()属性来删除以前添加的元素。

这是我的传奇代码 -

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

我想要的是当你选择属性DAMAGE_PROPERTY时它应该显示不同的图例。对于其他四个属性,它应该显示不同的图例。所以总共有两个传说。

0 个答案:

没有答案