0

I need help with ggplot. I have a big dataframe including different species collected in different years. For each species and year there are two samples and each sample represents a length frequency distributions. I need to create a ggplot function to plot the same plot for the different species, year, and sample. Hereunder the code for one plot taht I used several times:

ggplot(df, aes(x=lenClass, y=Ntot, fill=Sex)) +
geom_bar(stat="identity") + 
facet_grid(Year~DayTime) + theme_bw() +
xlab('CL mm') + ylab('No.individuals') +
ggtitle("StrataN1 - Sp1") +
theme(axis.title.x = element_text(size=13),
    axis.title.y  = element_text(size=13),
    plot.title = element_text(size = 14),
    strip.text.x = element_text(size=10.5),
    strip.text.y = element_text(size=8),
    axis.text.x  = element_text(size=8.5),
    axis.text.y  = element_text(size=7.5))

Thank you so much!

  • 1
    reproducible data please. an image of what the plot look like will help as well. – Adam Quek Jul 07 '16 at 09:30
  • check out the answer by Sven Hohenstein to a question I asked recently, maybe you can adapt it to your needs: http://stackoverflow.com/questions/34397876/writing-to-the-global-environment-from-a-function-in-r – yoland Jul 07 '16 at 10:27

1 Answers1

0

The trick is to have a loop over your classes. Within the loop, you can filter the data and do other data-preprocessing, then generate, display and save your plot.

library(ggplot2)

mainDF = iris
species = unique(mainDF$Species)
allPlots = list() #List to save plots

for(sp in species){ # For each class

  filteredDF = mainDF[mainDF$Species == sp,] # Filter dataframe  
  spPlot = ggplot(filteredDF, aes(x = Petal.Length, y = Petal.Width)) + geom_point() + ggtitle(sp) # Generate plot
  plot(spPlot) # Direct plotting
  allPlots[[sp]] = spPlot # Save plot to list

}
Deena
  • 5,925
  • 6
  • 34
  • 40