plotting multiple maps using rworldmap library

2019-04-14 23:25发布

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)

标签: r maps rworldmap
1条回答
淡お忘
2楼-- · 2019-04-15 00:02

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.

rworldmap multi-panel demo

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)
查看更多
登录 后发表回答