Skip to content

Instantly share code, notes, and snippets.

@aaronbalthaser
Last active November 8, 2017 16:48
Show Gist options
  • Save aaronbalthaser/88d212631ae83349e9de1cc458e3315d to your computer and use it in GitHub Desktop.
Save aaronbalthaser/88d212631ae83349e9de1cc458e3315d to your computer and use it in GitHub Desktop.
fresh block
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.links line {
stroke: #999;
stroke-opacity: 0.6;
}
.nodes circle {
stroke: #fff;
stroke-width: 1.5px;
}
</style>
</head>
<body>
<svg width="960" height="600"></svg>
<script>
var nodes_data = [
{"name": "Travis", "sex": "M"},
{"name": "Rake", "sex": "M"},
{"name": "Diana", "sex": "F"},
{"name": "Rachel", "sex": "F"},
{"name": "Shawn", "sex": "M"},
{"name": "Emerald", "sex": "F"}
];
var links_data = [
{"source": "Travis", "target": "Rake"},
{"source": "Diana", "target": "Rake"},
{"source": "Diana", "target": "Rachel"},
{"source": "Rachel", "target": "Rake"},
{"source": "Rachel", "target": "Shawn"},
{"source": "Emerald", "target": "Rachel"}
];
var width = 960;
var height = 600;
var svg = d3.select('svg');
var simulation = d3.forceSimulation(100)
.nodes(nodes_data)
.force('change_force',
d3.forceManyBody()
.strength(-100)
)
.force('center_force', d3.forceCenter(width / 2, height / 2))
.force('links', d3.forceLink(links_data).id((d) => {
console.log(d);
return d.name;
}));
var nodes = svg.append('g')
.attr('class', 'nodes')
.selectAll('circle')
.data(nodes_data)
.enter().append('circle')
.attr('r', 5)
.attr('fill', function(d) {
if (d.sex === "M") {
return 'red';
} else {
return 'blue';
}
});
var links = svg.append('g')
.attr('class', 'links')
.selectAll('line')
.data(links_data)
.enter().append('line')
.attr('stroke-width', 2);
simulation.on('tick', () => {
nodes
.attr('cx', (d) => {
return d.x;
})
.attr('cy', (d) => {
return d.y
});
links
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
});
console.log(links);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment