我正在尝试使用县的SVG文件和每个这样的数据的csv来制作一个chloropleth地图。我是D3的新手,并且使用了geoJSON。(谢谢Scott Murray)。 该示例将数据绑定到如下形状:
d3.json("us-states.json", function(json) {
//Merge the ag. data and GeoJSON
//Loop through once for each ag. data value
for (var i = 0; i < data.length; i++) {
var dataState = data[i].state; //Grab state name
var dataValue = parseFloat(data[i].value); //Grab data value, and convert from string to float
//Find the corresponding state inside the GeoJSON
for (var j = 0; j < json.features.length; j++) {
var jsonState = json.features[j].properties.name;
if (dataState == jsonState) {
//Copy the data value into the JSON
json.features[j].properties.value = dataValue;
//Stop looking through the JSON
break;
}
}
}
//Bind data and create one path per GeoJSON feature
svg.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", function(d) {
//Get data value
var value = d.properties.value;
if (value) {
//If value exists…
return color(value);
} else {
//If value is undefined…
return "#ccc";
}
});
但我很难将其改编为svg。我不需要让它创建路径 - 它们已经在那里,但是如何写一个基本上:“如果data.County ==路径id,将该行的数据绑定到路径”?
非常感谢任何帮助!!
答案 0 :(得分:1)
看看https://github.com/mbostock/d3/wiki/Selections#wiki-datum 做类似的事情:
// Where each path has an id
var paths = d3.selectAll('.my-paths path'),
elm,
data = [] // your data here,
your_criteria_here;
data.forEach(function (x, i, a) {
your_criteria_here = x.criteria;
// No data is available for the elements in this case yet
// @see https://github.com/mbostock/d3/wiki/Selections#wiki-each
paths.each(function (d, i) {
// Wrap dom element in d3 selection
elm = d3.select(this);
if (elm.attr('id') == your_criteria_here) {
// Do something here ...
}
});
});
请注意,此示例使用[] .forEach这是一个ecmascript 5功能(@see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach)