我有一个图表,其中沿着 x 轴的刻度线有圆形和矩形。我希望能够将所有元素集中在 x 轴的刻度上。圆形会自动放置在中心并使用半径属性进行缩放,但对于矩形,我无法移动它,因为我使用序数比例来创建 x 轴值。
这就是图表的样子:http://puu.sh/gmCkZ/37ab176161.png
可以看到,左上角的方 block 就是我想要的中心位置。
我的 x 轴代码如下所示:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], 1);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
d3.tsv("data.tsv", type, function(error, data) {
x.domain(data.map(function(d) { return d.name; }));
如何将像正方形这样的图形居中在某个位置?在这种情况下,在 x 轴的特定区域上?
编辑
添加了正方形的 SVG 代码:
var square = svgbody
.selectAll("nodes.rect")
.data(["B", "L"]);
square.exit()
.style("opacity", 1)
.transition()
.duration(500)
.style("opacity", 0)
.remove();
square.enter()
.append("rect")
.attr("class", "squareNodes");
square
.attr("x", function(d){ return x(d);})
.attr("y", function(d){return y(statusText);} )
.attr("width",19)
.attr("height",19)
.attr("rx", "3")
.attr("ry", "3" )
.style('opacity', NODE_OPACITY)
.style('fill', "green");
最佳答案
squareSize = 19;
square
.attr("x", function(d){ return x(d) - squareSize/2;})
.attr("y", function(d){return y(statusText) - squareSize/2;} )
.attr("width",squareSize)
.attr("height",squareSize)
...
关于javascript - 如何在 D3.js 中将矩形居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28866366/