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")
问题是,2张地图是按照计划创建的,但第二张地图的情节都取代了第一张地图。这发生在循环运行的第二次。我也试过[[1,exact=TRUE]],但都没有效果。
而第一个单独显示的图显示了所需的输出。如果在循环中第二次绘制,输出将被覆盖。
谁来帮帮我。被困了好几天
您将想要创建数据帧并在geom_point
中显式调用它-以下内容应该正确工作:
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))
}