Reputation: 16793
I am newbie in using d3 library, I am trying to have equal space between the legends. In the current stage of my work -attached- does not provide equal spaces.
I would like to know how I could able to fix.
Here is the code that I have so far:
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 })
},
Upvotes: 2
Views: 1581
Reputation: 3112
Here's an updated fiddle with what I think you're after: http://jsfiddle.net/henbox/7Le4tc92/2/
When you first draw the circle
and text
in each g
element, don't use a transform. Then, select each g
and get the text length (using getComputedTextLength()
) to calculate the translation you want:
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)"
})
Upvotes: 8