r2d3可视化中的范围-d3.selectAll与svg.selectAll

r2d3可视化中的范围-d3.selectAll与svg.selectAll,r,d3.js,r2d3,R,D3.js,R2d3,为什么d3.selectAll('rect')…不能像下面的mouseover函数中的脚本那样工作,但是svg.selectAll('rect')…可以工作 svg是r2d3中的特殊预设选择器 此外,我注意到,从Rstudio运行可视化时,从浏览器控制台运行例如d3.selectAll('rect').remove()不起作用 这来自r2d3示例,如sample.js: // !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20) var b

为什么
d3.selectAll('rect')…
不能像下面的mouseover函数中的脚本那样工作,但是
svg.selectAll('rect')…
可以工作

svg
是r2d3中的特殊预设选择器

此外,我注意到,从Rstudio运行可视化时,从浏览器控制台运行例如
d3.selectAll('rect').remove()
不起作用

这来自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通过r2d3::r2d3(“sample.js”,data=c(0.3,0.6,0.8,0.95,0.40,0.20))运行
默认情况下,r2d3将可视化放置在阴影DOM中。d3.select和d3.selectAll都从DOM的根元素开始搜索,但不要冒险进入阴影DOM的子节点

select和selectAll都不会从正在搜索的当前树交叉到阴影树中。由于
svg
是阴影DOM中元素的选择,因此可以使用
svg找到矩形。selectAll(“rect”)
但不是
d3。selectAll(“rect”)
(相对于svg,矩形没有“阴影”)

最简单的解决方案是不通过将r2d3 shadow选项设置为false来创建阴影DOM

例如(使用r2d3文件中的:


当然,这样做会丢失shadow root提供的封装,但这可能更可取或中立,具体取决于具体情况。

我发现有时r2d3.shadow选项并不总是很好地工作,因此这里有另一种可能的解决方案。事件目标的父对象将是您放置它的svg/g

// !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){
      const parent = d3.select(d.target.parentElement); // this is the original svg
      
      
      //svg.selectAll('rect').attr('fill', 'red')
      parent.selectAll('rect').attr('fill', 'blue')
      d3.select(this).attr('fill', 'red')
      
    })
// !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){
      const parent = d3.select(d.target.parentElement); // this is the original svg
      
      
      //svg.selectAll('rect').attr('fill', 'red')
      parent.selectAll('rect').attr('fill', 'blue')
      d3.select(this).attr('fill', 'red')
      
    })