Skip to content

Instantly share code, notes, and snippets.

@AndrewStaroscik
Last active December 17, 2015 22:59
Show Gist options
  • Save AndrewStaroscik/5686192 to your computer and use it in GitHub Desktop.
Save AndrewStaroscik/5686192 to your computer and use it in GitHub Desktop.
Working D3 nested selection

Functioning example of nesting elements within elements in D3 using transformations on the parent element and separate enter() for the array containing the child elements.

<!DOCTYPE html>
<meta charset="utf-8">
<div id="vis"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var parentElement = [
{name: "Path 1", startX: 25, startY: 75, segments: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]},
{name: "Path 2", startX: 25, startY: 125, segments: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}
];
var width = 500,
height = 200,
lineLength = 20;
var svg = d3.select("#vis").append("svg")
.attr("width", width)
.attr("height", height);
var g = svg.selectAll(".parent")
.data(parentElement);
var gEnter = g.enter()
.append("g")
.attr("class", "parent")
.attr('transform', function(d) { return 'translate(' + d.startX + ',' + d.startY + ')'; })
.style('fill', 'none')
.style('stroke', '#232323');
gEnter.selectAll(".child")
.data(function(d) {
console.log(d.segments);
return d.segments; })
.enter()
.append("line")
.attr('class', 'child')
.attr('x1', function(d,i) { return lineLength * d; })
.attr('y1', 0)
.attr('x2', function(d,i) { return lineLength * (1 + d); })
.attr('y2', 0);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment