如何在嵌套的D3对象上映射并创建数组
假设我使用D3-fetch命令将一些JSON数据从API返回到D3,并且数据是类似的嵌套对象:
{
"researcher": {
"deployment": 3.55974264705882,
"collaboration": 2.33547794117647,
"supportlevel": 3.19944852941176
},
"data": {
"deployment": 3.34428879310345,
"collaboration": 2.08836206896552,
"supportlevel": 2.953125
}
}
对于父组,我这样做是为了使它们成为用于在X-上绘制的变量Axis:
var groups = d3.map(data, function(d) {return(d)}).keys()
我的问题是,如何将儿童价值观(部署,协作,spupportlevel)纳入一个称为子组的变量,以便我可以在多与人图表上绘制?
显示条形的最终格式(每类3)将是这样:
// Show the bars
svg.append("g")
.selectAll("g")
// Enter in data = loop group per group
.data(data)
.enter()
.append("g")
.attr("transform", function(d) { return "translate(" + x(d.group) + ",0)"; })
.selectAll("rect")
.data(function(d) { return subgroups.map(function(key) { return {key: key, value: d[key]}; }); })
.enter().append("rect")
.attr("x", function(d) { return xSubgroup(d.key); })
.attr("y", function(d) { return y(d.value); })
.attr("width", xSubgroup.bandwidth())
.attr("height", function(d) { return height - y(d.value); })
.attr("fill", function(d) { return color(d.key); });
})
Let say I have some JSON data returned from an API to D3 using the d3-fetch command and the data is a a couple of nested objects like this:
{
"researcher": {
"deployment": 3.55974264705882,
"collaboration": 2.33547794117647,
"supportlevel": 3.19944852941176
},
"data": {
"deployment": 3.34428879310345,
"collaboration": 2.08836206896552,
"supportlevel": 2.953125
}
}
For the parent groups, I do this to get them into a variable for graphing on X-axis:
var groups = d3.map(data, function(d) {return(d)}).keys()
My question is how do I get the child values (deployment, collaboration, suppportlevel) into a variable called subgroups so I can plot on a multibar chart?
The final format to show the bars (3 per category) will be like this:
// Show the bars
svg.append("g")
.selectAll("g")
// Enter in data = loop group per group
.data(data)
.enter()
.append("g")
.attr("transform", function(d) { return "translate(" + x(d.group) + ",0)"; })
.selectAll("rect")
.data(function(d) { return subgroups.map(function(key) { return {key: key, value: d[key]}; }); })
.enter().append("rect")
.attr("x", function(d) { return xSubgroup(d.key); })
.attr("y", function(d) { return y(d.value); })
.attr("width", xSubgroup.bandwidth())
.attr("height", function(d) { return height - y(d.value); })
.attr("fill", function(d) { return color(d.key); });
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我仍然不确定哪种格式。以下2是正确的格式吗?
I'm still not sure what format. Is one of the following 2 is the right format?