R: How to create multiple maps (rworldmap) using a

2019-03-05 03:11发布

问题:

I want to create multiple maps (similar to this example) using the apply family. Here a small sample of my code (~200 rows x 150 cols). (UN and ISO3 are codes for rworldmap):

df <- structure(list(BLUE.fruits = c(12803543, 
    3745797, 19947613, 0, 130, 4), BLUE.nuts = c(21563867, 533665, 
    171984, 0, 0, 0), BLUE.veggies = c(92690, 188940, 34910, 0, 0, 
    577), GREEN.fruits = c(3389314, 15773576, 8942278, 0, 814, 87538
    ), GREEN.nuts = c(6399474, 1640804, 464688, 0, 0, 0), GREEN.veggies = c(15508, 
    174504, 149581, 0, 0, 6190), UN = structure(c(4L, 5L, 1L, 6L, 
    2L, 3L), .Label = c("12", "24", "28", "4", "8", "n/a"), class = "factor"), 
    ISO3 = structure(c(1L, 3L, 6L, 4L, 2L, 5L), .Label = c("AFG", 
    "AGO", "ALB", "ASM", "ATG", "DZA"), class = "factor")), .Names = c("BLUE.fruits", "BLUE.nuts", "BLUE.veggies", "GREEN.fruits", "GREEN.nuts", 
    "GREEN.veggies", "UN", "ISO3"), row.names = c(97L, 150L, 159L, 
    167L, 184L, 191L), class = "data.frame")

and the code I used before to plot one single map:

library(rworldmap)
mapDevice('x11')
spdf <- joinCountryData2Map(df, joinCode="ISO3", nameJoinColumn="ISO3")     
mapWF <- mapCountryData(spdf, nameColumnToPlot="BLUE.nuts", 
               catMethod="quantiles")

Note: in mapCountryData() I used the names of single columns (in this case "BLUE.nuts"). My question is: is there a way to apply this mapping code for the different columns creating six different maps? Either in one multi-panel using layout() or even better creating six different plots that get saved according to their colnames. Ideas? Thanks a lot in advance

回答1:

You are close.

Add this to save one plot per column.

#put column names to plot in a vector
col_names <- names(df)[1:6]


lapply(col_names, function(x) {
  #opens device to store pdf
  pdf(paste0(x,'.pdf'))
  #plots map
  mapCountryData(spdf, nameColumnToPlot=x)
  #closes created pdf 
  dev.off()
})