在ggplot2

时间:2016-07-10 19:18:44

标签: r loops plot ggplot2

我已经查看了这些问题123,但它们似乎解决了一个与我的案例无关的问题。通常,我使用此代码生成很好的多个图表,使用此代码

为我my normal plot工作
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)

graph2ppt(file="finalplots.pptx",aspectr=1.3)是我用来导出到ppt的东西。

我想为500多个变量制作单独的图,例如Ammonia,Asterorotalia(参见附图),并使用变量名保存单个文件或导出到ppt。我已经尝试了以下代码,但没有显示任何内容

###
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)
  }
}
下面的

是dput(head(plot1,10)),shapefile在这里可用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")

首先,让我为冗长的帖子道歉,我想尽可能提供一个可重复的例子。我很感激我能得到的任何帮助。谢谢

2 个答案:

答案 0 :(得分:3)

这将保存一系列图作为png图。我已修改了您dput数据,因此有两个属,因此有两个图。 (我不确定该功能的用途。)

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:如果要保存ggplot对象,我会将它们保存在命名列表中。

# 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"]]

答案 1 :(得分:0)

这是我的最终代码,以防任何人发现它有用,情节看起来像sample 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()
    }