在解决 d3 中的问题时遇到问题 - 我正在尝试将图例附加到我的 svg,并且我放入其中的文本需要分开,因此只有 d.key 由 colorScale 和d.total 位于 d.key 下方,填充为“黑色”。
这是我刚才提到的代码行 - .text(function(d) { return (d.key) + ' (' + d.total + ')'; })
简而言之,如何在 d.key 下面添加另一行文本并使该新文本的填充为“黑色”,或者只是不像 d.key 那样使用 colorScale 着色。
svg.append("g")
.attr("class", "legend")
.selectAll("text")
.data(layers)
.enter().append("text")
.text(function(d) { return (d.key) + ' (' + d.total + ')'; })
.attr('fill', function(d) { return colorScale(d.key); })
.attr('y', function(d, i) { return 50 * (i + 2.75); })
.attr('x', "375");
最佳答案
有多种方法可以做到这一点。两个独立的 text
元素包裹在 g
中,或者我下面显示的是两个 tspan
包裹在 text
中:
var svg = d3.select('body')
.append('svg')
.attr('width', 500)
.attr('height', 500);
var layers = [
{
key: 'one',
total: 10
}, {
key: 'two',
total: 20
}
];
var colorScale = d3.scale.category10();
var text = svg.append("g")
.attr("class", "legend")
.selectAll("text")
.data(layers)
.enter().append("text")
.attr('y', function(d, i) { return 50 * (i + 2.75); })
text.append("tspan")
.text(function(d) { return (d.key) + ' (' + d.total + ')'; })
.attr('fill', function(d) { return colorScale(d.key); })
.attr('x', "375");
text.append("tspan")
.attr("dy", "1.2em")
.attr("x", "375")
.text("Second row of text")
.style("fill", "black");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
关于javascript - SVG 元素 — 处理和选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170030/