Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex grid with d3.js

I'm currently trying to create a hex grid using d3.js and the hexbin plugin for d3.js. The problem I'm having is that I always have empty hexagons or entire empty rows in my grid instead of all hexagons nice together.

Any ideas how to fix this?

My code:

var margin = {
    top: 80,
    right: 20,
    bottom: 50,
    left: 80
},
width = $(window).width() - margin.left - margin.right,
height = $(window).height() - 28 - margin.top - margin.bottom;

var points = [];
for (var i = 0; i < 8; i++) {
    for (var j = 0; j < 12; j++) {
        points.push([Math.floor(width * j / 12), Math.floor(height * i / 8)]);
    }
}

var hexbin = d3.hexbin()
    .size([width, height])
    .radius((width / 12) / 2);

var svg = d3.select($("#grid").get(0)).append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
    .selectAll(".hexagon")
    .data(hexbin(points))
    .enter().append("path")
    .attr("class", "hexagon")
    .attr("d", function (d) {
    return hexbin.hexagon();
})
    .attr("transform", function (d) {
    return "translate(" + d.x + "," + d.y + ")";
})
    .attr("stroke", "#fff")
    .attr("stroke-width", "2px")
    .style("fill", function (d) {
    return "#dcdcdc"; //color(d.length); 
});
like image 717
jeroen.verhoest Avatar asked Jan 30 '13 09:01

jeroen.verhoest


1 Answers

Change your points data so that, when hexagons are added, the translation is not pushing them one hexagon too far right or one row too far down:

Something like this:

var points = [];
for (var i = 0; i < 8; i++) {
    for (var j = 0; j < 12; j++) {
        points.push([Math.floor(width * j / 14), Math.floor(height * i / 11)]);
    }
}
like image 146
mccannf Avatar answered Oct 01 '22 16:10

mccannf