因此,我为 Web 应用程序制作了一个条形图可视化,它会随着新数据的输入不断更新。
网络应用程序是 here .
如您所见,我可以在输入新数据时调整条形的宽度。这是我用来执行此操作的代码:
function updateBarChart(currentInfo) {
var bars = d3.select("#bar-chart")
.selectAll(".bar")
.data(currentInfo)
.transition()
.style("width", function(d) { return String(xScale(d.prob)) + "px"; });
var h2s = d3.select("#bar-chart")
.selectAll("h2")
.data(currentInfo)
.transition()
.text(function(d) { return d.title; });
var h1s = d3.select("#bar-chart")
.selectAll("h1")
.data(currentInfo)
.transition()
.text(function(d) { return String(Math.round(d.prob * 100)) + "%"; });
bars.enter().append("div")
.attr("class", "bar")
.transition()
.style("width", function(d) { return String(xScale(d.prob)) + "px"; })
bars.exit().remove()
h2s.enter().append("h2")
.transition()
.text(function(d) { return d.title; })
h2s.exit().remove()
h1s.enter().append("h1")
.transition()
.text(function(d) { return String(Math.round(d.prob * 100)) + "%"; })
h1s.exit().remove()
}
该函数的输入是具有以下形式的字典列表
{ title: 'title',
prob: probability(float)
}
出于某种原因,我不断收到错误消息“未捕获的类型错误:bars.enter 不是函数”。我查看了代码,它的灵感主要来自 this article on Medium.
我这里的代码有问题吗?我是 d3 的新手,所以我不确定我是否遗漏了一些重要的东西。
感谢任何帮助!谢谢!
最佳答案
问题:
如果您检查链接方法,您现在的“输入”选择等同于:
var bars = d3.select("#bar-chart")
.selectAll(".bar")
.data(currentInfo)
.transition()
.style("width", function(d) { return String(xScale(d.prob)) + "px"; })
.enter().append("div")
.attr("class", "bar")
.transition()
.style("width", function(d) {
return d + "px";
})
哪个行不通。
解决方案:
因为问题是 bars
变量应该只包含绑定(bind)数据,没有“更新”部分,这个 block :
var bars = d3.select("#bar-chart")
.selectAll(".bar")
.data(currentInfo)
.transition()
.style("width", function(d) { return String(xScale(d.prob)) + "px"; });
应该是:
var bars = d3.select("#bar-chart")
.selectAll(".bar")
.data(currentInfo);
bars.transition()
.style("width", function(d) { return String(xScale(d.prob)) + "px"; });
这样,您的“输入”选择将等同于此:
var bars = d3.select("#bar-chart")
.selectAll(".bar")
.data(currentInfo)
.enter().append("div")
.attr("class", "bar")
.transition()
.style("width", function(d) {
return d + "px";
})
这是使用您的(部分)代码的演示:
setInterval(function() {
var data = d3.range(~~(Math.random() * 20)+1)
.map(()=>~~(Math.random()*300));
updateBarChart(data);
}, 2000);
function updateBarChart(currentInfo) {
var bars = d3.select("body")
.selectAll(".bar")
.data(currentInfo);
bars.transition()
.style("width", function(d) {
return d + "px";
})
.text(function(d) {
return d;
});
bars.enter().append("div")
.attr("class", "bar")
.transition()
.style("width", function(d) {
return d + "px";
})
.text(function(d) {
return d;
});
bars.exit().remove();
}
.bar {
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
font: 10px sans-serif;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
关于javascript - selection.enter() 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40646198/