データの配列を受け取り、データ ポイントごとに四角形を作成し、四角形にテキストを表示する d3 ビジュアライゼーションを作成しました。ただし、座標を指定して、rect 内に表示するテキストを取得しただけです。rect 要素の中央に配置するようにどのように指示するのか疑問に思っています。コードは次のとおりです。
var elementTags = ["Google", "Amazon", "Wikipedia", "Yahoo!", "Messi", "Ronaldo", "One", "Two", "Three",
"Monkey"];
次の部分では、四角形を配置するために使用した配列を作成します
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]
幅と高さを設定する
var elementWidth = 210;
var elementHeight = 60;
svg コンテナーを作成し、四角形を追加します
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");
ここで、テキストを表示する場所を指定します。ここは、助けが必要な場所でもあります。テキストを四角形の中央に自動的に配置したい。
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;});