Skip to content

Instantly share code, notes, and snippets.

@idshklein
Created November 11, 2021 17:31
Show Gist options
  • Save idshklein/db039a7a9ebeb0745e4d15e2bd9ce05a to your computer and use it in GitHub Desktop.
Save idshklein/db039a7a9ebeb0745e4d15e2bd9ce05a to your computer and use it in GitHub Desktop.
library(tidyverse)
library(gganimate)
library(sf)
CLUSTERS <- 100
map(0:50,function(max.iter){
set.seed(12)
df <- data.frame(x = runif(100000,0,1000),
y = runif(100000,0,1000))
centers <- data.frame(x = 500 + runif(CLUSTERS,-100,100),
y = 500 + runif(CLUSTERS,-100,100))
if(max.iter > 0){
out <- kmeans(df,centers,iter.max = max.iter,algorithm = "Forgy")$centers %>% as.data.frame()
}else{
out <- centers
}
out$iter <- max.iter
out$point <- 1:CLUSTERS
out1 <- out %>%
st_as_sf(coords=c("x","y"))
env1 <- st_polygon(list(matrix(c(0,0,1000,0,1000,1000,0,1000,0,0),ncol=2, byrow=TRUE))) %>% st_sfc()
out2 <- out1 %>%
summarise() %>%
st_voronoi(env1) %>%
st_collection_extract() %>%
st_join(out1) %>%
st_intersection(env1) %>%
mutate(area = st_area(geometry))
out2
}) %>%
bind_rows() %>%
ggplot(aes(group = point,fill = log(area))) +
geom_sf() +
transition_states(iter) +
coord_sf(xlim = c(0,1000),ylim = c(0,1000)) +
scale_fill_viridis_c()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment