Reputation: 2230
I obviously having a hard time understanding something fundamental about wrapping g elements in D3 for a legend I am trying to render here. Does anyone why or how I can get this legend to display in a horizontal line like this legend does at the top?
Consider:
var wrap = svg.selectAll('.legend').append('g').data(color.domain());
var gEnter = wrap.enter().append('g').attr('class', 'legend')
.append('g');
var legend = wrap.select('g').style("width",1000)
.attr("transform", function(d, i) { return "translate(" + i * 20 + ",0)"; });
// draw legend colored circles
legend.append("circle")
.style("fill", color)
.style('stroke', color)
.attr('r', 5);
// // draw legend text
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d;});
Thanks in advance.
Upvotes: 1
Views: 1075
Reputation: 5817
You need to utilize transform
and translate
(transformation method) in order to get that effect. Also, another note, the circle and text for the legend really wont have any connection. In order to get that effect you must position them with the correct corresponding math. In my solution I am only using static numbers, but you will get the gist. In order to make it dynamic you will have to create some type of function that will dynamically calculate the positions.
Heres what I changed in order to get wanted behavior:
var legend = wrap.select('g').style("width",1000)
.attr("transform", function(d, i) { return "translate(" + i * 80 + ",0)"; });
// draw legend colored circles
legend.append("circle")
.style("fill", color)
.style('stroke', color)
.attr('r', 5)
.attr('transform', 'translate(550,20)');
// // draw legend text
legend.append("text")
.attr("dy", ".35em")
.attr('transform', 'translate(560,20)')
.text(function(d) { return d;})
and here is the fiddle: https://jsfiddle.net/yt2zhx63/
Upvotes: 1