Published
Edited
Apr 22, 2019
Insert cell
Insert cell
chart = {
const GRID_SIZE = 25;
const GRID_COLS = 6;
const GRID_ROWS = Math.ceil(data.nodes.length / GRID_COLS);
let grid = {
cells : [],
init : function() {
this.cells = [];
for(var c = 0; c < GRID_COLS; c++) {
for(var r = 0; r < GRID_ROWS; r++) {
var cell;
cell = {
x : c * GRID_SIZE,
y : r * GRID_SIZE,
occupied : false
};
this.cells.push(cell);
};
};
},
sqdist : function(a, b) {
return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);
},

occupyNearest : function(p) {
var minDist = 1000000;
var d;
var candidate = null;
for(var i = 0; i < this.cells.length; i++) {
if(!this.cells[i].occupied && ( d = this.sqdist(p, this.cells[i])) < minDist) {
minDist = d;
candidate = this.cells[i];
}
}
if(candidate)
candidate.occupied = true;
return candidate;
}
}
grid.init();
console.log(grid.cells);
const nodes = data.nodes.map(d => Object.create(d));

const simulation = d3.forceSimulation(nodes)
.force("center", d3.forceCenter(width / 2, height / 2))
const svg = d3.select(DOM.svg(width, height));

const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 5)
.attr("fill", color)
.call(drag(simulation));

node.append("title")
.text(d => d.id);
simulation.on("tick", () => {
grid.init();
node
.each(function(d) {
let gridpoint = grid.occupyNearest(d);
if (gridpoint) {
// ensures smooth movement towards final positoin
d.x += (gridpoint.x - d.x) * .05;
d.y += (gridpoint.y - d.y) * .05;
// jumps directly into final position
// d.x = gridpoint.x;
// d.y = gridpoint.y
}
})
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});

invalidation.then(() => simulation.stop());

return svg.node();
}
Insert cell
data = d3.json("https://gist.githubusercontent.com/mbostock/4062045/raw/5916d145c8c048a6e3086915a6be464467391c62/miserables.json")
Insert cell
height = 600
Insert cell
color = {
const scale = d3.scaleOrdinal(d3.schemeSet2);
return d => scale(d.group);
}
Insert cell
drag = simulation => {
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
Insert cell
d3 = require("d3@5")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more