英文:
D3.js script upgrade from v4 to v7
问题
我的 D3.js 图表在 v4 版本中运行良好,但在 v7 版本中出现问题。
我知道我必须在 v7 中使用 ".then" 子句,但我想理解下面函数的含义:" from :
...(d, i, columns ...)
...
to
...(return d)
...
它到底做什么?我该如何编写这个函数以在 v7 中使用?
d3.csv("20230316_data.csv", function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}, function(error, data) {
图表的说明
}
谢谢。
Jean-michel,法国
英文:
My D3.js graph works fine in v4 but not in v7.
I know I have to use the ".then" clause in v7 but I would like to understand the meaning of the function below " from :
...(d, i, columns ...)
...
to
...(return d)
...
What does it do exactly ? How can I code this function to use it in v7 ?
d3.csv("20230316_data.csv", function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}, function(error, data) {
instructions for the graph
}
Thank you.
Jean-michel, France
答案1
得分: 1
这是 D3 v4 中的 d3.csv
签名:
> d3.csv(url[[, row], callback])
请注意方括号表示某些参数是可选的。但要特别注意括号的嵌套:如果有两个参数,它们是:
d3.csv(url, callback)
如果您想要一种行转换函数,您需要三个参数:
d3.csv(url, row, callback)
这就是您所拥有的(不过您缺了一个括号)。这是您的行函数:
function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}
这是您的回调函数:
function(error, data) {
//图形的指令
}
在 D3 v7 中,该方法返回一个 promise(因此您可以使用 then()
,甚至 async
和 await
),并且具有此签名:
> d3.csv(input[, init][, row])
可以忽略 requestInit
。所以,在 D3 v7 中,您的方法将是:
d3.csv("20230316_data.csv", function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}).then(function(data) {
//图形的指令
})
英文:
This was the d3.csv
signature in D3 v4:
> d3.csv(url[[, row], callback])
Note that the square brackets mean some parameters are optional. However, pay close attention to the nesting of the brackets: if you have two parameters, they are:
d3.csv(url, callback)
If you want a row conversion function, you need three parameters:
d3.csv(url, row, callback)
And that's what you have (you are missing a parenthesis though). This is your row function:
function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}
And this is your callback:
function(error, data) {
//instructions for the graph
}
In D3 v7, the method returns a promise (so you can use it with then()
, or even async
and await
), and it has this signature:
> d3.csv(input[, init][, row])
The requestInit
can be ignored. So, your method in D3 v7 would be:
d3.csv("20230316_data.csv", function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] =
+d[columns[i]];
d.total = t;
return d;
}).then(function(data) {
//instructions for the graph
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论