在 Mike Bostock 编写的示例的帮助下,我使用 d3 制作了一张分区统计图。我是 d3 的新手(老实说,我是 HTML、JavaScript、CSS)。
我已经创建了 map 和图例,并且能够在不同的数据集之间切换。 map 和源代码可以在 bl.ocks.org 上查看
Glasgow Index of Deprivation 2012
我现在遇到的问题是如何在不同数据集之间切换时替换 map 和图例内容。正如您目前所看到的,当选择不同的数据集时,内容将简单地添加到现有内容之上。
我尝试遵循 Stephen Spann in this answer 给出的建议,以及他在工作 fiddle 中提供的代码。但没有效果。
据我了解,我应该像这样在开头添加 g 附加到 svg 变量......
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
然后像这样更新时选择它...
var appending = svg.selectAll("g")
.attr("class", "S12000046_geo")
.data(topojson.feature(glasgowdep, glasgowdep.objects.S12000046_geo).features);
// add new elements
appending.enter().append("path");
// update existing elements
appending.style("fill",
function (d) {
return color(choro[d.id]);
})
.style("stroke", "#cfcfcf")
.attr("d", path)
// rollover functionality to display tool tips
.on("mouseover", function (d) {
tip.show(d)
d3.select(this)
.transition().duration(200)
.style("fill", "red");
})
.on("mouseout", function () {
tip.hide()
d3.select(this)
.transition().duration(200)
.style("fill",
function (d) {
return color(choro[d.id]);
});
})
// build the map legend
var legend = d3.select('#legend')
.append('ul')
.attr('class', 'list-inline');
var keys = legend.selectAll('li.key')
.data(color.range());
var legend_items = ["Low", "", "", "", "", "", "", "", "High"];
keys.enter().append('li')
.attr('class', 'key')
.style('border-top-color', String)
.text(function (d, i) {
return legend_items[i];
});
// remove old elements
appending.exit().remove();
最佳答案
解决方案可能如下:在 http://bl.ocks.org/niallmackenzie/8a763afd14e195154e63 中的代码中尝试在构建 map 图例之前添加以下行(index.html 中的第 220 行):
d3.select('#legend').selectAll('ul').remove();
每次更新数据时,都会先清空#legend。
关于javascript - 如何使用 d3 更新/覆盖 map 和图例内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28874957/