为什么d3.selectAll('rect')...在鼠标悬停函数中的下面的脚本中不能正常工作,但svg.selectAll('rect')...可以?
svg是来自 r2d3 的特殊预设选择器。
此外,我注意到d3.selectAll('rect').remove()从浏览器控制台运行例如从 Rstudio 运行可视化时不起作用。
这是来自 r2d3 示例,如下所示sample.js:
// !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20)
var barHeight = Math.floor(height / data.length);
svg.selectAll('rect')
.data(data)
.enter().append('rect')
.attr('width', function(d) { return d * width; })
.attr('height', barHeight)
.attr('y', function(d, i) { return i * barHeight; })
.attr('fill', 'steelblue')
.on('mouseover', function(d){
d3.select(this).attr('fill', 'red')
//svg.selectAll('rect').attr('fill', 'red')
d3.selectAll('rect').attr('fill', 'red')
})
通过 R 从 R 运行r2d3::r2d3("sample.js", data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20))