p1 <- ggplot(d, aes(NYGN, SPAD))
wgss <- vector('numeric', 8)
plots <- vector('list', 9)
for(i in 2:9) {
km <- kmeans(x, centers = i)
wgss[i-1] <- km$tot.withinss
plots[[i-1]] <- p1 + geom_point(aes(color = factor(km$cluster))) +
scale_color_viridis(discrete = TRUE) +
theme(legend.position = 'none') +
ggtitle(paste('kmeans with', i, 'centers'))
}
plots[[9]] <- ggplot() + geom_point(aes(x = 2:9, y = wgss)) +
xlab('Number of Clusters') +
ylab('Within SS') +
ggtitle('Scree Plot')
do.call(plot_grid, c(plots, ncol = 3))
p1 <- ggplot(d, aes(NYGN, SPAD))
wgss <- vector('numeric', 8)
plots <- vector('list', 9)
clusters <- vector('list', 8)
for(i in 2:9) {
km <- kmeans(x, centers = i)
wgss[i-1] <- km$tot.withinss
clusters[[i-1]] <- km$cluster
}
scree <- ggplot() + geom_point(aes(x = 2:9, y = wgss)) +
xlab('Number of Clusters') +
ylab('Within SS') +
ggtitle('Scree Plot')
plots <- lapply(2:9,
function(i) {p1 +
geom_point(aes(color = factor(clusters[[i-1]]))) +
scale_color_viridis(discrete = TRUE) +
theme(legend.position = 'none') +
ggtitle(paste('kmeans with', i, 'centers'))
}
)
plots <- c(plots, list(scree))
do.call(plot_grid, c(plots, ncol = 3))