我的firestore数据库以以下方式保存: *集合为“测试” *文档“ Google自动生成的ID” *数据:2个数组,1是month_name = [1月,2月,3月,4月,5月] [2]是ac_output = [20、15、5、14、3]
我能够从数据库中检索数据,但是浏览器上没有显示任何矩形。然后,我尝试一次显示一个矩形,但仍然没有成功。我什至没有在控制台上收到任何错误,所以我不知道问题出在我的代码中。我真的需要帮助。谢谢
//Javascript Code:
//select the svg container
const svg = d3.select('.canvas')
.append('svg')
.attr('width', 600)
.attr('height', 600);
//get data from the firestore
db.collection('test').get().then(res => {
var data = [];
res.docs.forEach(doc => {
data.push(doc.data());
});
//append data to the rects in the DOM
const rects = svg.selectAll('rect')
.data(data);
//set the attributes for rects in DOM
rects.attr('width', 50)
.attr('height', function(...d) {
return d[0].ac_output})
.attr('fill', 'orange')
.attr('x', (d, i) => i*70)
//append the enter selection to the DOM
rects.enter()
.append('rect')
.attr('width',50)
.attr("height", function(...d) {
return(d[0].ac_output})
.attr('fill', 'orange')
})
目前预期的结果是浏览器上有一堆矩形,最终将其变成条形图。
如果我执行console.log(data),则此图像为输出:
答案 0 :(得分:0)
给出您的数据结构,实际上就是这样...
const data = [{
ac_output: [10, 15, 20, 15, 5, 9],
month_name: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
}];
...问题是您正在将仅包含一个元素的数组传递给data()
方法。在我看来,您想传递ac_outcome
中的值。在这种情况下,您的数据绑定应为:
const rects = svg.selectAll('rect')
.data(data[0].ac_output);
除此之外,您还有两个其他问题:
您在此处错误地使用了rest参数。首先是因为数据绑定,我们已经介绍过了。其次,因为这...
.attr("height", function(...d) {
})
...将通过以下参数传递数组:
a 。基准 b 。指数; c 。当前组;
因此,要使用该基准,应执行以下操作:
.attr("height", function(...d) {
//use d[0] here
})
但这没用,因为您可以轻松做到:
.attr("height", function(d) {
//use d here
})
这是您所做的更改的代码:
const svg = d3.select("svg");
const data = [{
ac_output: [10, 15, 20, 15, 5, 9],
month_name: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
}];
const rects = svg.selectAll('rect')
.data(data[0].ac_output);
rects.attr('height', function(d) {
return d;
});
rects.enter()
.append('rect')
.attr('width', 50)
.attr('x', (d, i) => i * 60)
.attr("height", function(d) {
return d
})
.attr('fill', 'orange')
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>