How to center text in a rect element in d3?
I have created a d3 visualization that takes an array of data, creats a rect for each data point, and then displays the text in the rect. However, I have only gotten the text to display inside of the rect by giving it coordinates. I am wondering how I would tell it to center itself in the rect element. Here is the code:
var elementTags = ["Google", "Amazon", "Wikipedia", "Yahoo!", "Messi", "Ronaldo", "One", "Two", "Three",
"Monkey"];
The next part creates arrays I used to position the rects
var xPosLoop = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3];
var yPosLoop = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]
set their width and height
var elementWidth = 210;
var elementHeight = 60;
create the svg container and add rects
var svgContainer = d3.select("body") //create container
.append("svg")
.attr("width", 1000)
.attr("height", 1000);
var enterElements = svgContainer.selectAll("rect") //draw elements
.data(elementTags).enter().append("rect")
.attr("x", function(d, i){
return xPosLoop[i]*(elementWidth+25);
})
.attr("height", elementHeight)
.attr("y", function(d, i){
return yPosLoop[i]*(elementHeight+35);
})
.attr("width", elementWidth)
.attr("rx", 4)
.attr("fill", "steelblue")
.attr("stroke", "black")
.attr("stroke-width", 1);
var addText = svgContainer.selectAll("text").data(elementTags).enter().append("text");
and here is where i tell the text where to display, it's also where I need help. I want the text to center itself in the rects automatically.
var textElements = addText
.attr("x", function(d, i){
return ((xPosLoop[i]*(elementWidth+25) +elementWidth/2))
})
.attr("y", function(d, i){
return ((yPosLoop[i]*(elementHeight+35)) + elementHeight/2 + 3)
})
.attr("font-family", "Arial Black")
.attr("font-size", "20px")
.attr("fill", "white")
.text(function(d, i){return d;});
It seems that your code properly computes the center of the rect and places the text at that point, except that the text is left aligned. If so, you just need to change the text-anchor
property to center the text. That would be:
textElements.style("text-anchor", "middle")