如上图,我给每个rect方块里面都放了一个text,能渲染出来,但是文字却没能显示,该怎么修改才能让它的文字显示在方块上面呢?
相关代码:
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x",function(d) { //每个矩形的起始x坐标
return padding.left + xScale(d[0]);
})
.attr("y",function(d){ //每个矩形的起始y坐标
return yScale(d[1]) + padding.bottom;
})
.attr("width",function(d){ //每个矩形的宽度
return xScale(d[2]);
})
.attr("height",26) //每个矩形的高度
.attr("fill",function() { //填充颜色
let color = ["#20a0ff","#F59DA6","#FBD0A1","#1ab394"];
return color[Math.floor(Math.random() * color.length)];
})
.append("text").text(function(d) { //添加文字描述
return d[3];
});
我们的做法是,把rect标签和text标签用一个g标签包裹,并列在一起,并调节text标签的dy属性,将其居中。