Skip to content
Prev 5864 / 7420 Next

Rarefaction curves in ggplot

Hi Ellen,

I was curious about this because I will be using a lot of vegan functions in a spring class. Turns out not to be trivial - as with all ggplot problems the trick is to get the data into a dataframe. I tried several things, but ended up writing my own function:

# rarefraction curves and ggplot
library("tidyverse")
library("vegan")
data(BCI)
out <- rarecurve(BCI, step = 10, sample = 400)
names(out) <- 1:50

as_tibble_rc <- function(x){
  # convert rarecurve() output to data.frame
  # bind_rows doesn't work because items are different lengths
  # also need to extract sample sizes from attribute 
  # Allocate result dataframe
  nsamples <- map_int(x, length)
  total_samples <- sum(nsamples)
  if(!is.null(names(x))){
    sites <- names(x)
  } else {
    sites <- as.character(1:length(nsamples))
  }
  result <- data_frame(Site = rep("", total_samples),
                       Sample_size = rep(0, total_samples),
                       Species = rep(0, total_samples))
  start <- 1
  for (i in 1:length(nsamples)){
    result[start:(start + nsamples[i]-1), "Site"] <- sites[i]
    result[start:(start + nsamples[i]-1), "Sample_size"] <- attr(x[[i]], "Subsample")
    result[start:(start + nsamples[i]-1), "Species"] <- x[[i]]
    start <- start + nsamples[i]
  }
  result
}

out <- as_tibble_rc(out)
# add grouping variable
sitedata <- data_frame(Site = as.character(1:50),
                       Type = sample(LETTERS[1:2], 50, replace = TRUE))
alldata <- left_join(out, sitedata, by = "Site")

# and then it's trivial
ggplot(data = alldata,
       mapping = aes(x = Sample_size, y = Species, color = Type, group = Site)) + 
  geom_line()

hope that helps.