Load in the modules and set the working directory.

library(ggplot2)
library(gridExtra)

setwd("~/Development/other_people_help/Annnabelle/stackplot")

First step is to read in your data and then split (using split()) the data frame up into five smaller data frames based on body parts. The results will be saved to a list of length 5 (df.ls) and each element will be a seperate data frame.

df <- read.csv("dfanalysis.csv")
df.ls <- split(df, df$Body.Part)

Okay, now we define a function to make our plots. It will be applied to each dataframe within the data frame list (df.ls).

plot.stack <- function(df){
  df <- df[!(df$Entanglement.Score==4),] # drop score 4
  df <- df[order(df$Year,df$Entanglement.Score),] # order the list based on year then score
  ggplot(df ,aes(x = Year, y = Entanglement.Score ,fill = as.factor(Entanglement.Score))) + 
    geom_bar(position = "fill", stat = "identity") +
    ggtitle(df$FLKbase[1]) # set title
}

The using lapply() we apply the function to every elment of the list and end up with a list of the plots (plot.ls).

plot.ls <- c(lapply(df.ls, plot.stack))

Then we work out how many plots we have and calculate how many columns we need and use the grid.arrange() function to plot them all together.

n <- length(plot.ls)
ncol <- floor(sqrt(n))

And there ya have it. You might want to modify the legend and axis titles but that should be easy. In this example though I’m just calling plot.ls so they come out properly in the html doc. Normally I would use do.call("grid.arrange", c(plot.ls, ncol=ncol))

# using plot.ls instead of do.call("grid.arrange", c(plot.ls, ncol=ncol))
plot.ls
## $DTS

## 
## $FLK

## 
## $FTS

## 
## $PTS

## 
## $VTS