Visualizing Plant Species Distribution by Year and Month Using R Plots.
# Split the data into individual plots by year
library(cowplot)
p.list <- lapply(sort(unique(dat1$spp.labs)), function(i) {
  ggplot(dat1[dat1$spp.labs==i & dat1$year == 2012, ],
         mapping=aes( 
           as.factor(month),as.factor(year), 
           fill=percent_pos))+
    geom_tile(size=0.1, colour="white") +
    scale_fill_gradientn(name="Percent (%) \npositive samples",
                         colours=rev(viridis(10)), limits=col.range,
                         labels=c("1%","25%","50%","75%","100%"),
                         breaks=c(0.01,0.25,0.5,0.75,1.0),
                         na.value="grey85") + 
    guides(fill = guide_colourbar(ticks = FALSE, label.vjust = 0.5,
                                  label.position = "right",
                                  title.position="top",
                                  title.vjust = 2.5))+
    scale_y_discrete(expand=c(0,0)) +
    scale_x_discrete(limits=as.factor(c(1:12)),
                     breaks = c(1,2,3,4,5,6,
                                7,8,9,10,11,12),
                     labels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", 
                                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")) +
    theme_minimal(base_size = 10) +
    labs(x="Month", y="", title="") + 
    theme(panel.border = element_rect(colour="black", fill=NA),
          axis.title.y = element_text(margin = margin(r=10)),
          axis.title.x = element_text(margin=margin(t=5)),
          axis.text.y=element_blank(),
          axis.text.x=element_text(angle=60, hjust=1),
          legend.position = "right",
          strip.background=element_rect(fill="grey95",colour="white"),
          strip.text.y.left = element_text(angle=0), 
          strip.placement="outside",
          plot.margin = margin(t=30),
          panel.spacing = unit(2.6,"lines")) +
    removeGrid()
})

# Combine the plots by year using cowplot
p <- draw(grobs, ncol=1, rel_heights = c(0.8, 0.15))
p.list <- lapply(p.list, function(i) {
  draw_grob(as_grob(i), x = 0.55, y = 0.02, width = 0.288, height = 1)
})
lapply(p.list, function(x) draw_grob(x, add = TRUE))
draw(p, add = TRUE)

Last modified on 2023-05-24