d3中传说之间的平等空间

时间:2015-04-01 16:29:32

标签: javascript d3.js

我是使用d3库的新手,我试图在传说之间有相同的空间。在我工作的当前阶段 - 附加 - 不提供相等的空间。

我想知道我是如何修复的。

enter image description here

这是我到目前为止的代码:

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 })
    },

1 个答案:

答案 0 :(得分:7)

这里有一个更新的小提琴我想你以后:http://jsfiddle.net/henbox/7Le4tc92/2/

首次在每个circle元素中绘制textg时,请勿使用转换。然后,选择每个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)"
    })
相关问题