[英]Using d3 - How do I select specific data from array to highlight when I click a button?
我有此数据:
var bardata = [10, 16, 7, 19, 18, 16, 23, 36, 31, 26, 20, 19, 23, 9, 26];
这些按钮:
var data = [{ "label": "US", "text": "US" }, { "label": "Germany", "text": "Germany" },
{ "label": "UK", "text": "UK" }, { "label": "Average", "text": "Average" }];
var diventer = d3.select("#buttons").selectAll("div")
.data(data)
.enter().append("div")
.style("display", "inline")
.style("margin", "10px")
.attr("id", function(data) { return data.label; });
diventer.append("button")
.text(function(data) { return data.text; });
我需要哪种选择器来选择bardata数组中的每个第3个元素,以便单击按钮时可以在图形上突出显示这些条形?
这是我目前在鼠标悬停时所拥有的,但是我知道按钮的位置必须有所不同:
.on('mouseover', function(d) {
tooltip.transition()
.style('opacity', .9)
tooltip.html(d)
.style('left', (d3.event.pageX - 35) + 'px')
.style('top', (d3.event.pageY - 30) + 'px')
tempColor = this.style.fill;
d3.select(this)
.style('opacity', .5)
.style('fill', 'yellow')
})
我在这里使用条形数据:
var myChart = d3.select('#chart').append('svg')
.style('background', '#E7E0CB')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate('+ margin.left +', '+ margin.top +')')
.selectAll('rect').data(bardata)
.enter().append('rect')
看起来bardata
数据中的数据不是唯一的,因此您不能真正使用D3的数据绑定来选择元素。 但是,您可以按索引过滤选择 :
d3.selectAll("rect").filter(function(d, i) { return i % 3 == 0; });
您需要更改特定按钮的测试; 例如,如果按钮的索引对应于其余部分:
.on("mouseover", function(d, i) {
d3.selectAll("rect").filter(function(e, j) { return j % 3 == i; });
});
通常,我强烈建议您提供使选择部分成为数据所需的信息,例如,为条形数据提供一个附加属性,告诉您条形属于哪个国家。 然后,您可以使用D3的数据匹配来基于此进行“选择”,或为每个rect
分配一个代表国家的类别,并根据该类别进行简单选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.