我有一个 svg map ,每个路径都有一个 class="county-code-###"。
还有一个包含县名称、县代码和县人口的 csv 文件。
我已启动以下操作,但不确定如何使用来自 csv 的日期填充正确的路径。
d3.text("counties.csv", function (datasetText) {
var parsedCSV = d3.csv.parseRows(datasetText);
var sampleHTML = d3.select("div")
.append("div")
.style("")
.style("")
.selectAll("path")
.data(parsedCSV)
.enter().append("path")
});
最佳答案
您可以使用datum
方法将区域名称(和 ID)添加到数据中。像这样的东西:
<script>
var height = 500;
var width = 700;
// generate a sample 'map'. This svg does not contain the names of the
// regions
var data = [{id:1, x:10, y:10}, {id:2, x:300, y:400}, {id:3, x:600, y:100}];
var vis = d3.select("#vis").append("svg")
.attr("width", width).attr("height", height);
vis.selectAll("rect").data(data).enter().append("rect")
.attr("x", function(d) { return d.x;})
.attr("y", function(d) { return d.y;})
.attr("width", 20).attr("height", 20)
.attr("class", function(d) { return "county-code-" + d.id;});
// Some sample data containing the region names; in this case hard coded,
// but could also be read from a csv file.
var data2 = [{id:1, name:"a"}, {id:2, name:"b"}, {id:3, name:"c"}];
// Add the names to the svg
vis.selectAll("rect").datum(function(d) {
// extract county code from class
var id = +d3.select(this).attr("class").match(/county-code-(\d+)/)[1];
d.id = id;
// look up id in data2; if found add name to datum
for (var i = 0; i < data2.length; i++) {
if (data2[i].id == id) {
d.name = data2[i].name;
break;
}
}
return d;
});
</script>
关于javascript - D3.js 使用 csv 文件中的数据填充 svg map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24731729/