1
library(ggplot2)
library(gridExtra)

date_start <- seq(as.Date("2015-01-01"), by = "1 day", length.out = 30)
date_end   <- seq(as.Date("2015-01-02"), by = "1 day", length.out = 30)

date <- data.frame(date_start = date_start,
                   date_end   = date_end)

date <- date[1:3, ] # to make this example shorter.

plots <- list()

for (i in 1:nrow(date)){

  json_string <- paste0("http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=",
                        date[i, 1],
                        "&endtime=",
                        date[i, 2],
                        "&minmagnitude=5")
  print(json_string)
  jsonData <- jsonlite::fromJSON(json_string)  

  magnitudes <- jsonData$features$properties$magi
  latitude   <- jsonData$features$geometry$coordinates[]

  long  <- (lapply(latitude,"[",1))
  long1 <- c(do.call("cbind",long)) 
  lat   <- lapply(latitude,"[",2)
  lat1  <- c(do.call("cbind",lat))  

  mp <- NULL 
  mapWorld <- borders("world", colour="gray50", fill="gray50")
  mp <- ggplot() + mapWorld 

  plots[[i]] <- mp + geom_point(aes(x=long1, y=lat1,size = (magnitudes)) ,color="blue")
}

grid.arrange(plots[[1]],plots[[2]], ncol = 1, main = "Earthquakes")

The problem is that 2 maps are created according to plan but both the plot of second map replaces the first one. And this happens in 2nd time the loop in run. Have also tried plots[[1,exact=TRUE]] but this did not work.

Whereas the first plot separately shown shows the required output. And if plotted after 2nd time in the loop the output is overridden.

Anybody please help. Been stuck for days.

JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
Ritesh Jung Thapa
  • 1,177
  • 2
  • 13
  • 20
  • [Start here](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – shekeine May 25 '15 at 10:58

1 Answers1

0

You're going to want to create data frame and call it explicitly in geom_point - the following should work correctly:

for (i in 1:nrow(date)){

  json_string <- paste0("http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=",
                        date[i, 1],
                        "&endtime=",
                        date[i, 2],
                        "&minmagnitude=5")
  print(json_string)
  jsonData <- jsonlite::fromJSON(json_string)  

  magnitudes <- jsonData$features$properties$magi
  coords     <- jsonData$features$geometry$coordinates[]

  long1 <- sapply(coords, "[", 1)
  lat1  <- sapply(coords, "[", 2)

  df <- data.frame(long1 = long1,
                   lat1  = lat1)

  mp <- NULL 
  mapWorld <- borders("world", colour="gray50", fill="gray50")
  mp <- ggplot() + mapWorld 

  plots[[i]] <- mp + 
    geom_point(data = df, aes(x = long1, y = lat1, size = (magnitudes)), color = "blue") +
    ggtitle(paste0("iteration: ", i))
}
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116