Hammao
Hammao

Reputation: 879

using loop for multiple plots in ggplot2

I've looked these questions 1, 2 and 3, but they appear to address a different problem and not relevant to my case. Usually, i use this code to produce nice multiple graphs that works for memy normal plot using this code

library(ggplot2)
library(maptools)
library (rgdal)
library (rgeos)
library(export)
library(ReporteRs)
library(ReporteRsjars)
library(rtable)
library(xtable)
library(taRifx)
library(devtools)
library(tidyr)
library(dplyr)
#Tidying up data from wide to long format
    plots <- read.delim("withoutPG3,23,24.txt")
    head(plots,5)
    ################   SUBSETTING DATA INTO 10 MANAGABLE PLOTS ###########################
    ###### PLOT 1
    plot1<- plots %>% 
      select(1:5,Ammonia, Asterorotalia, Bolivina, Bulimina, Cancris, Challengerella, Cibicides, Elphidium, Hanzawaia, Nonion)%>%
      gather(genus,`Relative Abundance (%)`, Ammonia, Asterorotalia, Bolivina, Bulimina, Cancris, Challengerella, Cibicides, Elphidium, Hanzawaia, Nonion)
    ############################################################################################################
    ## Loading the Persian Gulf shape fill referred to as iho
    PG <- readShapePoly("iho.shp")
    PG <- readOGR(dsn = ".", "iho")
    # convert to dataframe
    AG <- fortify(PG)
    #####################################################################################################
    background=ggplot()+ 
      geom_polygon(data=AG, aes(long, lat, group = group, fill = hole),
                   colour = alpha("black", 0.3), show.legend = FALSE)+
      scale_fill_manual(values = c("grey80", "white")) + 
    #######
      geom_point(data=plot1, aes(x=Longitude, y=Latitude, size=`Relative Abundance (%)`, 
                                 color="Red"))+
        scale_size_area("`Relative Abundance (%)`")+
      facet_wrap(~genus, ncol=4)+
        scale_x_continuous("", breaks=NULL) + 
      scale_y_continuous("", breaks=NULL)+
        annotate(geom="text", x=53, y=28,label="Iran",color="black", size = 3)+
      annotate(geom="text", x=48.5, y=26,label="Saudi \nArabia",color="black", size = 3)+
      annotate(geom="text", x=50.6, y=26,label="Bahrain",color="black", size = 3)+
      annotate(geom="text", x=51.2, y=25.3,label="Qatar",color="black", size = 3)+
      annotate(geom="text", x=56, y=24.5,label="United Arab \nEmirates",color="black", size = 3)+
      annotate(geom="text", x=57, y=25.7,label="Strait of \nHormuz",color="black", size = 3)
    #
    #
    background=background +theme_bw()+
      ggtitle("PERSIAN GULF")
    ###
    background=background +
      theme(plot.title = element_text(face="bold", size=15, vjust=1), 
            axis.title.y = element_text(face="bold", size=15),
            axis.title.x =element_blank(), 
            axis.text.x  = element_blank(),
            legend.position = c(.7, .15), 
            #legend.position = "top", 
            legend.title = element_text(colour="black", size=15, face="bold"),
            legend.text = element_text(colour="black", size=10, face="bold"))
    #
    background
    graph2ppt(file="finalplots.pptx",aspectr=1.3)

The graph2ppt(file="finalplots.pptx",aspectr=1.3) is what i use to export to ppt.

I will like to produce individual plots for over 500 variables e.g Ammonia, Asterorotalia (see e.g from the attached image) and save individual file using the variable names or export to ppt. I've tried the following code, but nothing is displayed

###
foram.graph <- function(plot1, na.rm = TRUE, ...){

  # create list of genus in data to loop over 
  foram_list <- unique(plot1$genus)

  # create for loop to produce ggplot2 graphs 
  for (i in seq_along(foram_list)) { 

    # create plot for each genus in plot1 
    forams <- ggplot()+ 

      geom_polygon(data=AG, aes(long, lat, group = group, fill = hole),
                   colour = alpha("black", 0.3), show.legend = FALSE)+
      scale_fill_manual(values = c("grey80", "white")) + 
      ########
      geom_point(subset(df, plot1$genus==foram_list[i]),
             aes(x=Longitude, y=Latitude, size=`Relative Abundance (%)`, 
                 color="Red")) + 
      scale_size_area("`Relative Abundance (%)`")+
      scale_x_continuous("", breaks=NULL) + 
      scale_y_continuous("", breaks=NULL)+
      theme_minimal() +
      ggtitle(paste(foram_list[i]))
    print(forams)
  }
}

below is dput(head(plot1, 10)) and the shapefile is available here iho shape file

structure(list(Labels = structure(c(1L, 12L, 25L, 27L, 28L, 29L, 
2L, 3L, 4L, 5L), .Label = c("PG 1", "PG 10", "PG 11", "PG 12", 
"PG 13", "PG 14", "PG 15", "PG 16", "PG 17", "PG 18", "PG 19", 
"PG 2", "PG 20", "PG 21", "PG 22", "PG 25", "PG 26", "PG 27", 
"PG 28", "PG 29", "PG 30", "PG 31", "PG 32", "PG 4", "PG 5", 
"PG 6", "PG 7", "PG 8", "PG 9"), class = "factor"), Latitude = c(26.54, 
26.54, 26.4503, 26.3333, 25.8333, 26.4333, 26.1333, 25.975, 26.635, 
26.3), Longitude = c(56.9503, 57, 55.5, 55.5, 54.9667, 54.4833, 
54.4833, 54.4833, 53.9667, 53.9842), Depth = c(0L, 0L, 21L, 23L, 
22L, 18L, 24L, 24L, 28L, 23L), Region = structure(c(2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("North", "South"), class = "factor"), 
    genus = c("Ammonia", "Ammonia", "Ammonia", "Ammonia", "Ammonia", 
    "Ammonia", "Ammonia", "Ammonia", "Ammonia", "Ammonia"), `Relative Abundance (%)` = c(1.79, 
    27.06, 8, 19.65, 3.86, 4.85, 0.35, 1.01, 0.92, 12.24)), .Names = c("Labels", 
"Latitude", "Longitude", "Depth", "Region", "genus", "Relative Abundance (%)"
), na.action = structure(c(3L, 5L, 61L, 62L, 63L, 64L, 65L, 66L, 
70L, 72L, 77L, 83L, 85L, 86L, 87L, 88L, 89L, 90L, 92L, 93L, 94L, 
95L, 96L, 101L, 102L, 106L, 116L, 119L, 122L, 123L, 134L, 135L, 
136L, 141L, 143L, 146L, 147L, 149L, 151L, 153L, 155L, 156L, 158L, 
159L, 160L, 161L, 163L, 168L, 169L, 171L, 172L, 173L, 175L, 176L, 
178L, 186L, 191L, 192L, 193L, 195L, 196L, 197L, 198L, 199L, 201L, 
202L, 208L, 210L, 213L, 215L, 220L, 233L, 234L, 238L, 239L, 242L, 
244L, 245L, 246L, 248L, 250L, 257L, 259L, 260L, 265L, 266L, 268L, 
269L, 272L, 274L, 275L, 277L, 278L, 281L, 282L), .Names = c("3", 
"5", "61", "62", "63", "64", "65", "66", "70", "72", "77", "83", 
"85", "86", "87", "88", "89", "90", "92", "93", "94", "95", "96", 
"101", "102", "106", "116", "119", "122", "123", "134", "135", 
"136", "141", "143", "146", "147", "149", "151", "153", "155", 
"156", "158", "159", "160", "161", "163", "168", "169", "171", 
"172", "173", "175", "176", "178", "186", "191", "192", "193", 
"195", "196", "197", "198", "199", "201", "202", "208", "210", 
"213", "215", "220", "233", "234", "238", "239", "242", "244", 
"245", "246", "248", "250", "257", "259", "260", "265", "266", 
"268", "269", "272", "274", "275", "277", "278", "281", "282"
), class = "omit"), row.names = c(1L, 2L, 4L, 6L, 7L, 8L, 9L, 
10L, 11L, 12L), class = "data.frame")

First, let me apologize for the lengthy post, I wanted to provide a reproducible example as much as possible. I'll appreciate any help I can get on this. Thank You

Upvotes: 2

Views: 7282

Answers (2)

Hammao
Hammao

Reputation: 879

Here is my final code in case anyone finds it useful and the plot looks like thissample image from the ppt file

    library(ggplot2)
    library(maptools)
    library (rgdal)
    library (rgeos)
    library(export)
    library(ReporteRs)
    library(ReporteRsjars)
    library(rtable)
    library(xtable)
    library(taRifx)
    library(tidyr)
    library(dplyr)
    #########
    # create list of genus in data to loop over 
    foram_list <- unique(plot1$genus)

    # create for loop to produce ggplot2 graphs 
    for (i in seq_along(foram_list)) { 
      df = subset(plot1, genus == foram_list[i])

      # create plot for each genus in plot1 
      forams <- ggplot() + 

        geom_polygon(data=AG, aes(long, lat, group = group, fill = hole),
                     colour = alpha("black", 0.3), show.legend = FALSE) +
        scale_fill_manual(values = c("grey80", "white")) +
        ########
        geom_point(data = df,
                   aes(x=Longitude, y=Latitude, size=`Relative Abundance (%)`, 
                       color="Red")) + 
        #scale_radius()+
        scale_size_area("`Relative Abundance (%)`")+
        scale_x_continuous("", breaks=NULL) + 
        scale_y_continuous("", breaks=NULL)+
        theme_minimal() +
        annotate(geom="text", x=53, y=28,label="Iran",color="black", size = 5)+
        annotate(geom="text", x=48.5, y=26,label="Saudi \nArabia",color="black", size = 5)+
        annotate(geom="text", x=50.6, y=26,label="Bahrain",color="black", size = 5)+
        annotate(geom="text", x=51.2, y=25.3,label="Qatar",color="black", size = 5)+
        annotate(geom="text", x=56, y=24.5,label="United Arab \nEmirates",color="black", size = 5)+
        annotate(geom="text", x=57, y=25.7,label="Strait of \nHormuz",color="black", size = 5)+
        ggtitle(foram_list[i])
      #
      forams=forams +
            theme(plot.title = element_text(face="italic", size=15, vjust=1), 
              axis.title.y = element_text(family = "Trebuchet MS", color="#666666", face="bold.italic", size=30),
              #family = "Trebuchet MS", color="#666666", face="bold",
              axis.title.x =element_blank(), 
              axis.text.x  = element_blank(),
              legend.position = c(.8, .8), 
              #legend.position = "top", 
              legend.title = element_text(colour="black", size=15, face="bold"),
              legend.text = element_text(colour="black", size=10, face="bold"))
      #
      graph2ppt(x=forams,file="forams.pptx",append=TRUE)
      dev.off()
    }

Upvotes: 1

Sandy Muspratt
Sandy Muspratt

Reputation: 32859

This will save a series of plots as png plots. I've modified you dput data so that there are two genera, and thus two plots. (I'm not sure of the purpose of the function.)

library(ggplot2)
library(rgdal)
library(rgeos)
library(maptools)

# Loading the Persian Gulf shapefile
PG <- readShapePoly("iho.shp")
PG <- readOGR(dsn = ".", "iho")

# convert to dataframe
AG <- fortify(PG)

# Modify your dput data so that there are two genera
plot1$genus = rep(c("AAA", "BBB"), 1)

  # create list of genus in data to loop over 
  foram_list <- unique(plot1$genus)

  # create for loop to produce ggplot2 graphs 
  for (i in seq_along(foram_list)) { 
     df = subset(plot1, genus == foram_list[i])

  # create plot for each genus in plot1 
     forams <- ggplot() + 

     geom_polygon(data=AG, aes(long, lat, group = group, fill = hole),
        colour = alpha("black", 0.3), show.legend = FALSE) +
        scale_fill_manual(values = c("grey80", "white")) +
      ########
      geom_point(data = df,
             aes(x=Longitude, y=Latitude, size=`Relative Abundance (%)`, 
                color="Red")) + 
      scale_size_area("`Relative Abundance (%)`")+
      scale_x_continuous("", breaks=NULL) + 
      scale_y_continuous("", breaks=NULL)+
      theme_minimal() +
      ggtitle(foram_list[i])

png(paste0(foram_list[i], ".png"), 4, 4, "in", res = 100)
print(forams)
dev.off()
}

OR: If you want to save the ggplot objects, I would save them in a named list.

# create list of genus in data to loop over 
foram_list <- unique(plot1$genus)

# Initialise the list
forams = list()

# create for loop to produce ggplot2 graphs 
for (i in seq_along(foram_list)) { 

   df = subset(plot1, genus == foram_list[i])

    # create plot for each genus in plot1 
    forams[[i]] <- ggplot() + 

      geom_polygon(data=AG, aes(long, lat, group = group, fill = hole),
                   colour = alpha("black", 0.3), show.legend = FALSE) +
      scale_fill_manual(values = c("grey80", "white")) +

      geom_point(data = df,
             aes(x=Longitude, y=Latitude, size=`Relative Abundance (%)`, 
                color="Red")) + 
      scale_size_area("`Relative Abundance (%)`")+
      scale_x_continuous("", breaks=NULL) + 
      scale_y_continuous("", breaks=NULL)+
      theme_minimal() +
      ggtitle(foram_list[i])
}

names(forams) = foram_list

forams[["AAA"]]
forams[["BBB"]]

Upvotes: 4

Related Questions