2
votes

I have a dataset with different species and year of their observation (in 3 categories). I would now like to make one plot per species with their observations per year and assign each year-category (each bar) a different color, but it should be the same colour in every plot.

I tired to do lapply and then do a ggplot with geom_bar (see code below). I know I can assign the colours with geom_bar(fill = c("#e31a1c", "#ff7f00", "#33a02c") but the problem is, that there are species, that were only observed in some of the years, so I get an error that the aesthetics are not the same length as the data. So is there another way to assign the colours to the bars?

Species = c(rep("X", 7), rep("Y", 3), rep("Z", 4), "V", rep("W", 3))
Year = c("A", "A", "A", "B", "B", "C", "C","A", "A", "C","B", "B", "C", "C","A", "A", "B", "C")
df <- data.frame(Species, Year)

mylist = lapply(split(df, as.factor(df$Species)), function(memefin){
  ggplot(memefin, aes(x = Year, fill = Year))+
    geom_bar(fill = c("#e31a1c", "#ff7f00", "#33a02c"))+
    ggtitle(memefin$Species)+
    scale_x_discrete(breaks=c("A","B","C"),labels=c("2000-2004", "2005-2009", "2010-2014"), drop = F)
})
1
Could you show a sample of current and ideal plots?NelsonGon

1 Answers

2
votes

You are on the right track:

mylist = lapply(split(df, as.factor(df$Species)), function(memefin){
 ggplot(memefin, aes(x = Year, fill = Year))+
   geom_bar()+
   ggtitle(memefin$Species)+
   scale_x_discrete(breaks=c("A","B","C"),labels=c("2000-2004", "2005-2009", "2010-2014"), drop = F)+
   scale_fill_manual(values=c("A"="#e31a1c","B"= "#ff7f00","C" ="#33a02c")) # just apply the colours to specific "Years"
})