javascript - 在 D3 v6 中制作 choropleth 时如何解决“不可迭代”的问题?
问题描述
我现在正在尝试使用 d3.js 版本 6 构建一个 choropleth。这是我在 JavaScript 中的代码:
var height = 300;
var projection = d3.geoMercator().center([145, -36.5])
.translate([width/2, height/2])
.scale(2450);
var color = d3.scaleQuantize().range(['#b2182b','#ef8a62','#fddbc7','#d1e5f0','#67a9cf','#2166ac']);
var path = d3.geoPath().projection(projection);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("fill", "grey");
d3.csv("files/VIC_LGA_unemployment.csv", function(data) {
//Set input domain for color scale
color.domain([
d3.min(data, function(d) { return d.value; }),
d3.max(data, function(d) { return d.value; })
]);
d3.json("files/LGA_VIC.json").then(function(json) {
for (var i = 0; i < data.length; i++) {
var data_LGA = data[i].LGA;
//Grab data value, and convert from string to float
var dataValue = parseFloat(data[i].unemployed);
for (var j = 0; j < json.features.length; j++) {
var json_LGA = json.features[j].properties.LGA_name;
if (data_LGA == json_LGA) {
//Copy the data value into the JSON
json.features[j].properties.value = dataValue;
//Stop looking through the JSON
break;
}
}
}
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";
}
});
});
});
但是,当我尝试在 Firefox 上运行可视化时,它说我有一个 TypeError(t 不可迭代),如下图所示:
任何熟悉 D3 中的 choropleth 的人都可以帮我解决这个问题吗?
谢谢!
解决方案
答案实际上是这个的副本,但这里建议的方法可能是一种更清洁的方法。
( d3.csv
and d3.json
) 方法在 v4 和 v5 之间更改为使用fetch
API 即 Promises。因此,您使用这些功能的基本方式应该从:
d3.csv('file.csv', function(data) {...});
至:
d3.csv('file.csv')
.then(function(data) {...})
.catch(function(err) { console.log(err); });
其中 D3 v6 仍在使用 v5 中引入的这种方式。
您收到t is not iterable
错误是因为d3.min()
(and max
) 函数使用for...of
数组来找出答案,并且在您调用它们时,数据的 Promise 尚未解决。
您已经在使用d3.json("files/LGA_VIC.json").then(function(json) {
,但也许您可以Promise.all
像这样考虑使用,然后重构您的代码:
Promise.all([
d3.csv("./data.csv"),
d3.json("./map.json")
])
.then(function([data, map]) {
console.log(`There are ${data.length} rows of data`);
console.log(`There are ${map.features.length} features in the geojson`);
// ... join data to features and then draw chloropeth
});
推荐阅读
- c - `WM_MOUSEMOVE` 中的奇怪坐标
- mysql - 有没有办法查看特定列的分类内容?
- c# - RabbitMQ C# AMQP 在尝试连接本地主机时被中断
- c# - wpf 使进度条可从方法访问
- admob - 如何让 Google Admob 验证我的身份?
- python - Dash python - 基于熊猫列的图像回调
- javascript - 如何创建将拦截 vanilla js 中的任何属性和函数调用的模拟对象?
- python - 如何在 SublimeREPL 中使用虚拟环境?
- jmeter - 使用ppk文件的Jmeter SSH SFTP
- python - Odoo 11 - 过滤 Many2One 字段