Skip to content

Instantly share code, notes, and snippets.

@chichacha
Last active October 6, 2019 04:45
Show Gist options
  • Save chichacha/3375cd17b51d781491f9a651dc97f8a7 to your computer and use it in GitHub Desktop.
Save chichacha/3375cd17b51d781491f9a651dc97f8a7 to your computer and use it in GitHub Desktop.
Random Shape with sf - geometry
rm(list = ls())
library(sf)
library(tidyverse)
library(ggthemes)
## Generate some random data
df <- tibble(
grp = sample(LETTERS[1:18], size=300, replace=T),
x = rbeta(n=300, shape1=1, shape2=1),
y = rbeta(n=300, shape1=1.5, shape2=2),
) %>% mutate(idx=as.numeric(factor(grp))-1,
y = (idx%%3)+y,
x = floor(idx/3)+x)
## Rotate Function
rot = function(a) matrix(c(cos(a), sin(a), -sin(a), cos(a)), 2, 2)
rot(pi/2)
df_sf <-df %>%
st_as_sf(coords=c("x","y"), dim="XY") %>%
#st_set_crs(4326) %>%
group_by(grp) %>%
summarise(geometry = st_combine(geometry),
center = st_centroid(geometry),
geom_hull = st_convex_hull(geometry),
geom_hull_rot = (geom_hull - center) * rot(pi/2) + center ) %>%
st_cast("LINESTRING") %>%
st_cast("POLYGON")
df_sf
df_sf %>% ggplot() +
geom_sf(aes(fill=grp), color="#ffffff", size=0, alpha=0.5) +
geom_sf(aes(color=grp, geometry=geom_hull),fill="#ffffff00",size=1) +
geom_sf(aes(color=grp, geometry=geom_hull_rot), fill="#ffffff00", size=1) +
geom_sf(aes(geometry=center), shape=4, color="white") +
scale_fill_tableau("Hue Circle", guide="none") +
scale_color_tableau("Hue Circle", guide="none") +
theme_void() +
theme(plot.background = element_rect(fill="gray8")) +
expand_limits(x=c(0,6), y=c(-0.5,3.5)) ## just giving extra space
ggsave(file="~/Downloads/RandomShape.png", width=12, height=8)
@chichacha
Copy link
Author

RandomShape

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment