d3.js图例:组之间的水平间距
我一直在尝试在饼图中添加水平图例。如何根据文本长度将组隔开d3.js图例:组之间的水平间距,d3.js,D3.js,我一直在尝试在饼图中添加水平图例。如何根据文本长度将组隔开 const legend = d3 .select("svg") .append("g") .attr( "transform", "translate("200, 10")" ) .selectAll("g") .data(this.data
const legend = d3
.select("svg")
.append("g")
.attr(
"transform",
"translate("200, 10")"
)
.selectAll("g")
.data(this.dataset)
.enter()
.append("g");
legend
.append("rect")
.attr("fill", "green")
.attr("height", 15)
.attr("width", 15);
legend
.append("text")
.attr("x", 18)
.attr("y", 10)
.attr("dy", ".15em")
.text((d) => d.label)
.style("text-anchor", "start")
.style("font-size", 12);
首先,您应该为容器添加类,因为您需要重新选择它们 然后您应该尝试实现完整的d3更新模式(除非您不更改数据,否则您的图例将不会更新) 假设g.legend是您的图例容器,g.legendItem是不同的项目,每个项目都有一个rect和一个文本 您需要选择所有legendItems并循环浏览它们,例如,使用.each 以totalWidth=0开始 对于每一个,测量宽度(item.getBBox().width),将容器转换到正确的位置,并增加totalWidth,然后移动到下一个位置 下面是一个例子:
var totalWidth = 0;
items = svg.selectAll('g.legendItems')
.each(function() {
var current = d3.select(this);
current.attr('transform', `translate(${totalWidth}, 0)`);
totalWidth += current.node().getBBox().width + 5;
});