Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  128] [ 4]  / answers: 1 / hits: 41378  / 11 Years ago, sat, may 18, 2013, 12:00:00

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;});

More From » d3.js

 Answers
56

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)

[#78154] Thursday, May 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaac

Total Points: 645
Total Questions: 109
Total Answers: 96

Location: Cayman Islands
Member since Fri, Mar 4, 2022
2 Years ago
;