Skip to content

Instantly share code, notes, and snippets.

@ramhiser
Created November 19, 2011 03:31
Show Gist options
  • Save ramhiser/1378388 to your computer and use it in GitHub Desktop.
Save ramhiser/1378388 to your computer and use it in GitHub Desktop.
Generate Uniform Clusters and Plot with ggplot2
library('plyr')
library('reshape2')
library('ggplot2')
bivar_unif <- function(n, a1, b1, a2, b2) {
cbind(runif(n, a1, b1), runif(n, a2, b2))
}
gen_unif <- function(n = 25, delta = 0, seed = NULL) {
if(is.null(seed)) {
seed <- delta
}
set.seed(seed)
pop1 <- c(-1/2, 1/2, delta - 1/2, delta + 1/2)
pop2 <- c(delta - 1/2, delta + 1/2, -1/2, 1/2)
pop3 <- c(-1/2, 1/2, -delta - 1/2, -delta + 1/2)
pop4 <- c(-delta - 1/2, -delta + 1/2, -1/2, 1/2)
unif_pops <- rbind.data.frame(pop1, pop2, pop3, pop4)
colnames(unif_pops) <- c("a1", "b1", "a2", "b2")
unif_pops$n <- n
x <- mdply(unif_pops, as.data.frame(bivar_unif), .expand = F)
colnames(x) <- c("Population", "x1", "x2")
x$Population <- as.factor(x$Population)
x
}
x <- gen_unif(25, 2)
p <- ggplot(x, aes(x = x1, y = x2, group = Population))
p + geom_point(aes(color = Population))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment