Skip to content

Instantly share code, notes, and snippets.

@ottadini
Created November 29, 2013 00:08
Show Gist options
  • Save ottadini/7699787 to your computer and use it in GitHub Desktop.
Save ottadini/7699787 to your computer and use it in GitHub Desktop.
Functions and code to create a hexagonal grid.
# Cannot remember the source for this code, it isn't mine.
genHexGrid <- function(dx, ll = c(0, 0), ur = c(1, 1))
{
dy <- sqrt(3) * dx / 2
x <- seq(ll[1], ur[1] - dx / 2, dx)
y <- seq(ll[2], ur[2], dy)
y <- rep(y, each = length(x))
x <- rep(c(x, x + dx / 2), length.out = length(y))
x <- x + (ur[1] - max(x)) / 2
y <- y + (ur[2] - max(y)) / 2
list(x = x, y = y)
}
genPolyList <- function(hexGrid)
{
dx <- hexGrid$x[2] - hexGrid$x[1]
dy <- dx / sqrt(3)
x.offset <- c(-dx / 2, 0, dx / 2, dx / 2, 0, -dx / 2)
y.offset <- c(dy / 2, dy, dy / 2, -dy / 2, -dy, -dy / 2)
f <- function(i) list(x = hexGrid$x[i] + x.offset,
y = hexGrid$y[i] + y.offset)
lapply(1:length(hexGrid$x), f)
}
xy <- genHexGrid(0.05)
plot(xy, asp = 1, axes = F, pch = 19, xlab = NA, ylab = NA, cex = 0.5)
lapply(genPolyList(xy), polygon, xpd = NA, ypd = NA)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment