下面是包含文本的矩形的代码。
问题是它似乎无法对齐。如何让它们更容易对齐?
这是我使用的代码:
我知道我可以调整矩形和文本的 x
和 y
,但是一种更有条理的方式让它们对齐可能是有一个 g
每个矩形和相关文本,并调整它们在 g
内的位置?如何实现这一目标?
<!DOCTYPE html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.8/d3.min.js" type="text/JavaScript"></script>
<!--script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.9/d3.js" type="text/JavaScript"></script-->
<style>
rect {
stroke: #9A8B7A;
stroke-width: 1px;
fill: #CF7D1C;
opacity:
}
</style>
<body></body>
<script>
var dataset = [[1,3,3,5,6,7],[3,5,8,3,2,6],[9,0,6,3,6,3],[3,4,4,5,6,8],[3,4,5,2,1,8]];
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var local = d3.local();
svg.append("g")
.selectAll("g")
.data(dataset)
.enter()
.append("g")
.selectAll("text")
.data(function(d, i) {
local.set(this, i)
return d;
})
.enter()
.append("text")
.text(function(d, i, j) {
return d;
})
.attr("x", function(d, i, j) {
return (i * 20) + 40;
})
.attr("y", function(d) {
return (local.get(this) * 20) + 40;
})
.attr("font-family", "sans-serif")
.attr("font-size", "20px");
svg.append("g")
.selectAll("g")
.data(dataset)//use top-level data to join g
.enter()
.append("g")
.selectAll("rect")
.data(function(d, i) {//for each <g>, use the second-level data (return d) to join rect
console.log(this);
local.set(this, i);//this is the <g> parent
return d;
})
.enter()
.append("rect")
.attr("x", function(d, i, j) {
return (i * 20) + 40;
})
.attr("y", function(d) {
return (local.get(this) * 20) + 40;
})
.attr("width",20)
.attr("height",20)
.attr("fill-opacity",0.1)
</script>
最佳答案
一个简单的解决方案就是设置 dominant-baseline 。这是一个很好的图像,具有可能的值:
来源:http://bl.ocks.org/eweitnauer/7325338
因此,就您而言,只需执行以下操作:
.attr("dominant-baseline", "text-before-edge")
这是经过更改的代码:
var dataset = [
[1, 3, 3, 5, 6, 7],
[3, 5, 8, 3, 2, 6],
[9, 0, 6, 3, 6, 3],
[3, 4, 4, 5, 6, 8],
[3, 4, 5, 2, 1, 8]
];
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var local = d3.local();
svg.append("g")
.selectAll("g")
.data(dataset) //use top-level data to join g
.enter()
.append("g")
.selectAll("rect")
.data(function(d, i) {
local.set(this, i); //this is the <g> parent
return d;
})
.enter()
.append("rect")
.attr("x", function(d, i, j) {
return (i * 20) + 40;
})
.attr("y", function(d) {
return (local.get(this) * 20) + 40;
})
.attr("width", 20)
.attr("height", 20)
.attr("fill", "tan")
.attr("stroke", "dimgray")
.attr("fill-opacity", 0.4);
svg.append("g")
.selectAll("g")
.data(dataset)
.enter()
.append("g")
.selectAll("text")
.data(function(d, i) {
local.set(this, i)
return d;
})
.enter()
.append("text")
.text(function(d, i, j) {
return d;
})
.attr("x", function(d, i, j) {
return (i * 20) + 40;
})
.attr("y", function(d) {
return (local.get(this) * 20) + 40;
})
.attr("dominant-baseline", "text-before-edge")
.attr("font-family", "sans-serif")
.attr("font-size", "20px");
<script src="https://d3js.org/d3.v4.min.js"></script>
关于d3.js - 文本和矩形未对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46630697/