plotting multiple maps using rworldmap library

我们两清 提交于 2019-12-06 13:51:30

问题


I want to plot multiple maps using rworldmap, where each column is a separate month and the rows are years. I know this can be done in ggmap using facet_grid. How can I do this using rworldmap?

For example, the mydata file contains columns for the latitude, longitude, month and year of each point. My code so far:

library(rworldmap)
newmap <- getMap(resolution = "high")
plot(newmap, xlim = c(110, 155), ylim = c(-35, -20), asp = 1)
p1 <- read.csv("mydata.csv")
points(p1$lon, p1$lat, col = "red", cex = .5)

回答1:


To plot multiple maps using rworldmap, you could use layout and a couple of loops to create a plot like this using the code below.

I know loops aren't cool these days but I still think that way. Probably possible to put all this into an apply type function, but the speed of the loops is rarely an issue when plotting.

(also see item 19 multi-panel plots in the FAQ http://cran.r-project.org/web/packages/rworldmap/vignettes/rworldmapFAQ.pdf )

library(rworldmap)
newmap <- getMap(resolution = "coarse") #'low' or even 'coarse' resolution map may be sufficient

#example data for 2 years 6 months each
month <- c(1:6,1:6)
year <- c(rep(2012,6),rep(2013,6))
lon <- c(120:131)
lat <- c(-35:-24)
p1 <- data.frame(month=month,year=year,lon=lon,lat=lat)

months <- unique(p1$month)
years <- unique(p1$year)

oldPar <- par(mar=c(2, 0, 0, 2)) #margins top,bottom,left,right

#use layout to create multiple panels including space at top for a title
nPanels <- layout( cbind(c(0,1:6),c(0,7:12))
                   , heights=c(lcm(1),rep(1,6))
                   , respect=F )


for( yrNum in 1:length(years) )
{
  yr <- years[yrNum]
  for( moNum in 1:length(months) )
  {
    mo <- months[moNum]

    cat(yr,mo,"\n")

    plot(newmap, xlim = c(110, 155), ylim = c(-35, -20), asp = 1)
    mtext( paste(yr,"month",mo), cex=0.7) #add titile to subplot

    pMoYr <- p1[ p1$year==yr & p1$month==mo, ]

    points(pMoYr$lon, pMoYr$lat, col = "red", cex = 3)
  }
}

mtext("rworldmap layout demo",outer=TRUE,line=-2)

par(oldPar)


来源:https://stackoverflow.com/questions/19439689/plotting-multiple-maps-using-rworldmap-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!