d3 中的图例之间等于 Space

Equal Space between the legends in d3

我是使用 d3 库的新手,我试图让图例之间的 space 相等。在我工作的当前阶段 -attached- 不提供相等的 spaces。

我想知道如何修复。

这是我目前的代码:

var margin = { top: 20, right: 50, bottom: 30, left: 60 };

    self.drawLegends = function () {

            var legendData = [{ "color": "blue", text: "Normal Distribution" }, { color: "green", text: " Ave A" }, { color: "red", text: "Ave B" }]
            var legends = self.svg.selectAll("g legends").data(legendData);
            var legendBox = legends.enter()
                 .append("g")
                 .attr("transform", function (d, i) { return "translate(" + parseFloat((i + 1) * (($("#chart").width() - margin.left - margin.right) / 4)) + ",-10)" })

        var circles = legendBox.append("circle")
            .attr("r", 5)
            .attr("stroke", "black")
            .attr("fill", function (d, i) { return d.color })

        legendBox.append("text")
           .attr("dx", function (d) { return 10 })
           .attr("dy", function (d) { return 5 })
           .attr("fill","white")
           .text(function (d) { return d.text })
    },

这是更新后的 fiddle,我认为您想要的是:http://jsfiddle.net/henbox/7Le4tc92/2/

第一次在每个 g 元素中绘制 circletext 时,不要使用变换。然后,select每个g并获取文本长度(使用getComputedTextLength())来计算你想要的翻译:

svg.selectAll("g")
    .attr("transform", function (d, i) {
        var x_pos = d3.select(this).select("text").node().getComputedTextLength() + 20;
        x_offset = x_offset + x_pos;
            return "translate(" + (x_offset - x_pos + margin.left) + ", 20)"
    })