javascript-D3-如何使用条形图的键循环遍历对象
作者:互联网
我正在尝试使用下面的数据集创建条形图.我被卡在确定bar [country]的height [score]的部分上.如何遍历数据集以提取不同国家/地区的每个分数?
任何帮助将不胜感激 :)
var w = 500;
var h = 100;
var barPadding = 1;
var dataset = [
{"country":"Hong Kong","score":8.98},
{"country":"Singapore","score":8.54},
{"country":"New Zealand","score":8.19},
{"country":"Switzerland","score":8.09},
{"country":"Mauritius","score":8.98},
{"country":"United Arab Emirates","score":8.05},
{"country":"Canada","score":8.00},
{"country":"Australia","score":7.87},
{"country":"Jordan","score":7.86},
{"country":"Chile","score":7.84},
];
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - (d * 4);
})
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d) {
return d * 4;
});
解决方法:
在D3中,通过.data(dataset)命令加载数据后,您现在可以通过插入匿名函数function(d,i){}来访问数据的每条记录,就像在一些属性中所做的那样.
由于您的数据集是:
var dataset = [
{"country":"Hong Kong","score":8.98},
{"country":"Singapore","score":8.54},
{"country":"New Zealand","score":8.19},
{"country":"Switzerland","score":8.09},
{"country":"Mauritius","score":8.98},
{"country":"United Arab Emirates","score":8.05},
{"country":"Canada","score":8.00},
{"country":"Australia","score":7.87},
{"country":"Jordan","score":7.86},
{"country":"Chile","score":7.84},
];
每个d是一个对象记录,例如{“ country”:“ Singapore”,“ score”:8.54},而我指的是返回的对象d的索引,例如上面使用的d的示例为1.
要访问对象记录d的分数,这将成为简单的Javscript对象表示法,即d.score.
因此,您的.attr调用应如下所示:
.attr("height", function(d) {
return d.score * 4;
});
同样,您可以提取其他字段,例如如果您打算在.attr(“ text”,function(d){return d.country;})中使用d.country的国家/地区;
这是D3的真正魅力和力量.如果要使用通过数据获得的更多功能扩展可视化效果,则只需确保数据集数据包含更多数据属性,您就可以在以后遍历匿名函数时调用它们. D3本着其名称的精神,真正做到了“数据驱动”!
标签:d3-js,javascript,object,nested-loops 来源: https://codeday.me/bug/20191120/2046959.html