Skip to content

Instantly share code, notes, and snippets.

@cpsievert
Last active November 7, 2015 06:35
Show Gist options
  • Save cpsievert/9969fda38b4b944e85b9 to your computer and use it in GitHub Desktop.
Save cpsievert/9969fda38b4b944e85b9 to your computer and use it in GitHub Desktop.
# function to get a long-form of a correlation matrix
tidy_cor <- function(x) {
co <- as.data.frame(x)
co$var1 <- row.names(co)
dat <- tidyr::gather(co, var2, cor, -var1)
dat$var1 <- factor(dat$var1, levels(dat$var2))
dat
}
d <- tidy_cor(cor(mtcars))
d$id <- paste(d$var1, d$var2, sep = "-")
library(animint)
p1 <- ggplot() +
geom_tile(aes(x = var1, y = var2, fill = cor, clickSelects = id),
data = d) +
scale_fill_gradient2() + xlab("") + ylab("")
# Implementing multiple clickSelects would greatly reduce the complexity and increase efficiency
nms <- names(mtcars)
vars <- combn(nms, 2, simplify = F)
vars <- c(vars, lapply(vars, rev))
ids <- lapply(vars, paste, collapse = "-")
dats <- Map(function(x, y) setNames(cbind(mtcars[x], y), c("x", "y", "id")), vars, ids)
d2 <- do.call("rbind", dats)
d2$id <- as.character(d2$id)
p2 <- ggplot() +
geom_point(aes(x = x, y = y, showSelected = id), data = d2)
animint2dir(list(p1 = p1, p2 = p2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment