Skip to content

Instantly share code, notes, and snippets.

@fnshr

fnshr/hex_sf.R

Last active Jul 22, 2018
Embed
What would you like to do?
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