【问题标题】:Accessing properties of objects in D3 histogram bins访问 D3 直方图 bin 中对象的属性
【发布时间】:2013-09-15 04:49:12
【问题描述】:
我正在开发一个 D3.js 项目,以显示从 CSV 文件中提取的一些学生测试结果的直方图。除了原始考试成绩外,我还有一些关于 CSV 中每个学生的其他人口统计数据。我希望能够将鼠标悬停在直方图中的任何特定条上,并显示有关该条中代表的学生的一些汇总统计信息。
是否可以访问构成直方图条的数组中包含的记录的其他属性?如果是这样,有人知道我可以检查的示例吗?
【问题讨论】:
标签:
javascript
csv
d3.js
data-visualization
【解决方案1】:
使用histogram 布局会抛出除用于创建直方图箱的标量之外的所有内容。
可能有更好的方法,但由于其他学生属性没有附加到每个栏,只需在原始学生数组中搜索那些分数在鼠标悬停的 bin 中的学生:
.on('mouseover',function(d){
console.log('data bound to bars ' + d);
var selectedStudents = values.filter(function(record){
return d.x <= record.score && record.score < d.x + d.dx; });
console.log(selectedStudents.map(function(record){ return record.name; }));
});
http://bl.ocks.org/1wheel/6568151
selectedStudents 数组可用于生成除列出名称之外的其他摘要统计信息。
【解决方案2】:
您可以在鼠标悬停事件期间在条形图顶部显示工具提示。这个想法是让一个 div 浮动在 svg 区域的顶部。您可以在工具提示中显示各种信息。请参阅此处的示例:
http://vida.io/documents/F3Ehr3qqeK28P22wn
这是显示/隐藏工具提示的代码块:
on("mouseover", function(d) {
var bar_width = parseInt($(this).attr("width"), 10);
var x = parseInt($(this).attr("x"), 10) + bar_width / 2 + 5;
var y = parseInt($(this).attr("y"), 10) - 20;
div.transition().duration(200).style("opacity", 1);
// include info you want to display here:
div.html(d[X_AXIS_COLUMN] + "<br/>" + Y_DATA_FORMAT(d[Y_AXIS_COLUMN])).style("left", x + "px").style("top", y + "px");
}).on("mouseout", function(d) {
div.transition().duration(500).style("opacity", 0);
})