Skip to content

Instantly share code, notes, and snippets.

@eclarke
Created April 8, 2014 19:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eclarke/10178083 to your computer and use it in GitHub Desktop.
Save eclarke/10178083 to your computer and use it in GitHub Desktop.
Some r code relating to heatmaps and OTU counts
prop_presence_absence <- function(otu.pa, groups) {
# Creates a proportional presence-absence melted dataframe suitable for use in
# ggplot heatmaps to show varying within-group proportions of species.
#
# Args:
# otu.pa: Matrix of presence-absence data. Columns are samples, rows are
# species.
# groups: Grouping data frame. A column named "SampleID" should be unique
# list of sample identifiers that match the column names of otu.pa.
# The other column, named "group", should correspond to the group
# assignment of each sample.
otu.melt = melt(otu.pa, varnames=c("otu", "SampleID"))
otu.melt = merge(otu.melt, groups, by="SampleID")
otu.cast = dcast(otu.melt, formula=otu~group, value.var="value",
fun.aggregate=mean)
otu.melt = melt(otu.cast)
return(otu.melt)
}
ggheatmap <- function(otu_counts, ncolors=20, saturation_lim=0.8) {
# Creates a heatmap from a melted otu count/abundance matrix. Assumes that the
# x axis will correspond to the column named "variable" in the melted data frame,
# and the y axis will be the "otu" column. The "value" column will be used for
# the tile values, and the color scale uses Kyle's saturated_rainbow function.
colors = scale_fill_gradientn(colours=saturated_rainbow(ncolors, saturation_lim),
na.value="white")
p = ggplot(data=otu_counts, aes(x=variable, y=otu)) +
geom_tile(aes(fill=value)) + colors
return(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment