我有两个并排的 d3 choropleth map ,两者都从相同的 geojson 绘制,但代表不同年份(当前和 2014 年)的不同数据。
我加载两个不同年份的数据:
var currentMap = d3.map();
var map2014 = d3.map();
d3.queue()
.defer(d3.csv, "data/overdoses_2018_updated.csv", function(d) {
if (isNaN(d.DrugOverdoseMortalityRate)) {
console.log('nan')
} else {
currentMap.set(d.FIPS, +d.DrugOverdoseMortalityRate);
}
})
.defer(d3.csv, "data/overdoses_2014_updated.csv", function(e) {
if (isNaN(e.DrugOverdoseMortalityRate)) {
console.log('nan')
} else {
map2014.set(e.FIPS, +e.DrugOverdoseMortalityRate);
}
})
.await(ready);
并成功渲染当年的 map -
//GeoPath
var geoPath = d3.geoPath()
.projection( albersProjection );
d3.select("svg.current").selectAll("path")
.data( CaliforniaCountiesOverdoses.features )
.enter()
.append( "path" )
.attr( "d", geoPath )
.attr("class","counties")
.attr("fill", function(d) {
var value = currentMap.get(d.properties.ID);
return (value != 0 ? current_color(value) : "grey");
})
// setting popup based on current data
.on("mouseover", function(d) {
countyDiv .html('<br/>' + d.properties.NAME + '<br/>' + d.properties.DrugOverdo + ' overdoses per 10,000')
})
现在,我在 2014 年也这样做:
d3.select("svg.map2014").selectAll("path")
.data( CaliforniaCountiesOverdoses.features )
.enter()
.append( "path" )
.attr( "d", geoPath )
.attr("class","counties-2014")
.attr("fill", function(e) {
var value2014 = map2014.get(e.properties.ID);
return (value2014 != 0 ? current_color(value2014) : "grey");
})
// trying to set popup based on 2014 data
.on("mouseover", function(e) {
county2014Div .html('<br/>' + e.properties.NAME + '<br/>' + e.properties.DrugOverdo + ' overdoses per 10,000')
一切都很完美 - 县填充颜色反射(reflect)了 2014 年的数据,但输入到 County2014Div 的 html 不是 2014 年的数据,它仍然是当前的数据。如何让它从 2014 年数据源而不是当前数据源读取 d.properties?提前致谢。
最佳答案
您正在使用 CaliforniaCountiesOverdoses.features
中找到的数据。
就像在 fill()
中执行的操作一样,根据 path
的 ID 查找值。
d3.select("svg.map2014").selectAll("path")
.data( CaliforniaCountiesOverdoses.features )
.enter()
.append( "path" )
.attr( "d", geoPath )
.attr("class","counties-2014")
.attr("fill", function(e) {
var value2014 = map2014.get(e.properties.ID);
return (value2014 != 0 ? current_color(value2014) : "grey");
})
.on("mouseover", function(e) {
var value2014 = map2014.get(e.properties.ID);
county2014Div .html('<br/>' + e.properties.NAME + '<br/>' + value2014 + ' overdoses per 10,000');
通过删除所有重复代码,您的代码可以大大简化。
关于javascript - 来自 2 个不同数据源 (d3.js) 的 d.properties 的内部 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451194/