Skip to content

Instantly share code, notes, and snippets.

@fnshr
Last active July 22, 2018 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fnshr/bd752961f12dee4670d0c2ab1923e0c9 to your computer and use it in GitHub Desktop.
Save fnshr/bd752961f12dee4670d0c2ab1923e0c9 to your computer and use it in GitHub Desktop.
Create a hexagonal map as an sf object
if(!require("sf")){
install.packages("sf")
library("sf")
}
hex_sf <- function(x, y, radius = 1){
stopifnot(length(y) == length(x) &&
is.integer(x) && is.integer(y))
center_x <- sqrt(3) * radius * x +
sqrt(3) / 2 * radius * y
center_y <- 1.5 * radius * y
hex_polygon <- function(center_x, center_y, radius){
st_polygon(list(cbind(
cos(pi/2 + pi/3 * c(0:5,0)) * radius + center_x,
sin(pi/2 + pi/3 * c(0:5,0)) * radius + center_y)))
}
sfc <- st_sfc(Map(hex_polygon, center_x, center_y, radius))
st_sf(data.frame(X=x, Y=y, hexCX = center_x, hexCY = center_y,
geom=sfc))
}
if(!require("ggplot2")){
install.packages("ggplot2")
library("ggplot2")
}
x1 <- c(-1L, 0L, 0L, 1L, 1L, 2L, 2L, 2L)
y1 <- c(-1L, -1L, 0L, 1L, 2L, 1L, 2L, 3L)
hexmap1 <- hex_sf(x1, y1)
ggplot(hexmap1) + geom_sf() +
geom_text(aes(hexCX, hexCY,
label = paste(X, Y, sep=", ")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment