我正在学习 D3 JS,我正在尝试复制 D3 条形图教程 here .它像使用 d3.v3 一样工作,但是当我通过更改将 src 更改为 d3.d5 时:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
//Irrelevant CSS...
</style>
<svg class="chart"></svg>
<script src="https://d3js.org/d3.v5.min.js"></script> //Changed to d3.v5
<script>
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width);
d3.tsv("data.tsv", type, function(error, data) {
x.domain([0, d3.max(data, function(d) { return d.value; })]);
chart.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", function(d) { return x(d.value); })
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d.value) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d.value; });
});
function type(d) {
d.value = +d.value; // coerce to number
return d;
}
</script>
我收到一个错误:
Uncaught (in promise) TypeError: chart.selectAll(...).data(...).enter is not a function
我宁愿学习最新最好的,我假设是 D3.v5,而不是 D3.v3,除非后者确实是最新的稳定版本。此方法链中是否有语法更改?因为我想
.selectAll(...).data(...).enter
将是一个非常“标准”的方法链。不幸的是,这令人惊讶地抵抗了谷歌搜索;类似的问题是更复杂的用例,具有更多的自由度,而我的问题只涉及更改 D3 版本。
最佳答案
我发现您的解决方案有两个问题:
d3.tsv("data.tsv", type, function(error, data) {
至 d3.tsv("data.tsv").then(function(data) {
解释2:d3.tsv函数返回一个promise,需要先解析才能使用数据
关于d3.js - D3Js.v5 : . ..selectAll(...).data(...).enter 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54085560/