D3.js 向D3平行坐标中的轴标签添加背景色

D3.js 向D3平行坐标中的轴标签添加背景色,d3.js,parallel-coordinates,D3.js,Parallel Coordinates,我正在为平行坐标修改版本。我想为轴标签添加背景色。我意识到我不能使用CSS样式设置背景颜色,因为这是SVG文本,所以我尝试附加矩形,但没有效果。这是我写的,但没有画任何东西: d3.selectAll(".label") .append("rect") .attr("x", function(d){ return d3.select(this).node().getBBox().

我正在为平行坐标修改版本。我想为轴标签添加背景色。我意识到我不能使用CSS样式设置背景颜色,因为这是SVG文本,所以我尝试附加矩形,但没有效果。这是我写的,但没有画任何东西:

           d3.selectAll(".label")  
                      .append("rect")
                        .attr("x", function(d){ return d3.select(this).node().getBBox().x - 5;})
                        .attr("y", function(d){ return d3.select(this).node().getBBox().y - 5;})
                        .attr("width", function(d){ return d3.select(this).node().getBBox().width;})
                        .attr("height", function(d) {return d3.select(this).node().getBBox().height;})
                        .style("stroke", "black")
                        .style("fill", "yellow");
我做错了什么? 编辑: 根据注释,我将附加到父g而不是文本标签本身。现在代码如下所示:

  // Add an axis and title.
                 var gsvg= g.append("svg:g")
                      .attr("class", "axis")
                      .attr("id", "gsvg")
                      .each(function(d) { d3.select(this).call(axis.scale(yscale[d])); })
                      .attr("transform", "translate(0,0)");

                    d3.selectAll("#gsvg")  
                      .append("rect")
                        .attr("x", function(d){ return this.parentNode.getBBox().x - 5;})
                        .attr("y", function(d, i){ return i%2 === 0 ? this.parentNode.getBBox().y - 20: this.parentNode.getBBox().y - 35;})
                        .attr("width", function(d){ return this.parentNode.getBBox().width;})
                        .attr("height", function(d) {return 20;})
                        .style("stroke", "lightgrey")
                        .style("stroke-width", 2)
                        .style("fill", function(d){
                            return self.fcolorMap[d];
                        })
                        .style("opacity", 0.5);

                    gsvg.append("svg:text")
                      .style("text-anchor", "middle")
                      .attr("y", function(d,i) { return i%2 == 0 ? -14 : -30 } )
                      .attr("x",0)
                      .attr("class", "axis-label")
                      .text(function(d) { 
                        var s = d.split("|");
                        return s[s.length-1]; });

唯一的问题是现在我需要弄清楚如何得到标签的边界框,而不是轴的边界框

您的选择是一组文本元素吗?因为您无法将rect附加到文本元素。类似于此的答案可能有助于找到合适的方法:感谢您的有用评论。我尝试附加到父g,现在绘制了矩形。唯一的问题是,我似乎无法得到标签的边界框,而不是轴的边界框。一个截图是我根据你的建议编辑了我的问题,添加了更新的代码。现在可以了。我只是交换了将文本附加到矩形之前的顺序,这使得parentNode.getBBox()返回了正确的值。谢谢你的帮助。请随意添加您的评论作为答案。