Skip to content

Instantly share code, notes, and snippets.

@zkamvar
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zkamvar/91686d5d5d0bb2f14a38 to your computer and use it in GitHub Desktop.
Save zkamvar/91686d5d5d0bb2f14a38 to your computer and use it in GitHub Desktop.
Visualize poppr population hierarchies with treemap
#==============================================================================#
# Visualize the population hierarchy of a genclone object.
#
# Packages needed (install beforehand):
library(poppr)
library(treemap)
#==============================================================================#
# Main function
#
# Inputs:
# x - a genclone object
# h - a hierarchical formula (see examples below)
# show - if TRUE, the plot will be displayed, if FALSE, the data necessary
# to create the plot will be displayed.
# ... - any arguments passed on to the treemap function.
make_treemap <- function(x, h = NULL, show = TRUE, ...){
if (is.null(h)){
hier <- unique(strata(x))
} else {
hier <- unique(strata(x, h, combine = FALSE))
}
form <- make_formula(names(hier))
setPop(x) <- form
hier$Count <- table(pop(x))
if (show){
return(treemap(hier, all.vars(form), "Count", ...))
} else {
return(c(list(dtf = hier, index = all.vars(form), vSize = "Count"), ...))
}
}
make_formula <- function(x){
if (is.language(x)){
return(x)
} else {
return(as.formula(paste0("~", paste(x, collapse = "/")), env = .GlobalEnv))
}
}
#==============================================================================#
# EXAMPLES
#==============================================================================#
# Using P. infestans data
data(Pinf)
make_treemap(Pinf, title = "P. infestans")
make_treemap(Pinf, ~Country, title = "P. infestans")
# Using A. euteiches data
data(Aeut)
strata(Aeut) <- other(Aeut)$population_hierarchy[-1]
make_treemap(Aeut, ~Pop/Subpop, vColor = "Pop", type = "categorical", title = "A. euteiches")
# Using M. fructicola data
data(monpop)
splitStrata(monpop) <- ~Tree/Year/Symptom
# Don't show the plot and pass it to do.call
trees <- make_treemap(monpop, type = "categorical", vColor = "Tree", show = FALSE, title = "M. fructicola")
names(trees)
head(trees$dtf)
do.call("treemap", trees)
# here's a better plot without the tree labels.
make_treemap(monpop, type = "categorical", vColor = "Tree", title = "M. fructicola",
align.labels = list(c("center", "top"), c("center", "center"), c("center", "bottom")),
fontsize.labels = c(0, 15, 15))
@zkamvar
Copy link
Author

zkamvar commented Dec 10, 2014

To run use:

# If you don't have these packages:
install.packages("treemap")
install.packages("poppr")

devtools::source_gist("91686d5d5d0bb2f14a38")

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